diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/authentication/apikey/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/authentication/apikey/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/authentication/apikey/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/authentication/apikey/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/authentication/apikey/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/authentication/apikey/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/authentication/apikey/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/authentication/apikey/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/pyproject.toml index a72c01ac2082..f7b2ad805460 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-api-key/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/authentication/http/custom/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/authentication/http/custom/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/authentication/http/custom/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/authentication/http/custom/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/authentication/http/custom/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/authentication/http/custom/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/authentication/http/custom/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/authentication/http/custom/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/pyproject.toml index 374275073802..e598834f323c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-http-custom/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/authentication/noauth/union/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/pyproject.toml index 06298f5944df..bb74a54432e6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-noauth-union/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/pyproject.toml index 475e43b540d4..ff11017f51b5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/authentication/union/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/authentication/union/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/authentication/union/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/authentication/union/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/authentication/union/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/authentication/union/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/authentication/union/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/authentication/union/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/pyproject.toml index 3be63bda8833..c31cd4a1a76b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-union/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/pyproject.toml index a99e4bd807f2..9dbc0b6f837e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/operations/_operations.py index 232da02d2e35..010c05fb603c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/operations/_operations.py @@ -562,7 +562,7 @@ async def _operation(self, *, name: str, **kwargs: Any) -> _models._models.Outer { "name": "Madge" } - }. + } :keyword name: Required. :paramtype name: str @@ -629,7 +629,7 @@ async def _discriminator(self, *, kind: str, **kwargs: Any) -> _models._models.A { "name": "Madge", "kind": "real" - }. + } :keyword kind: Required. :paramtype kind: str diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/operations/_operations.py index 28dc23f3bb65..edc6dbb7aac0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/operations/_operations.py @@ -731,7 +731,7 @@ def _operation(self, *, name: str, **kwargs: Any) -> _models._models.OuterModel: { "name": "Madge" } - }. + } :keyword name: Required. :paramtype name: str @@ -798,7 +798,7 @@ def _discriminator(self, *, kind: str, **kwargs: Any) -> _models._models.Abstrac { "name": "Madge", "kind": "real" - }. + } :keyword kind: Required. :paramtype kind: str diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/types.py deleted file mode 100644 index 02f81f1cac29..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-access/specs/azure/clientgenerator/core/access/types.py +++ /dev/null @@ -1,129 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Literal, Union -from typing_extensions import Required, TypedDict - - -class BaseModel(TypedDict, total=False): - """Used in internal operations, should be generated but not exported. - - :ivar name: Required. - :vartype name: str - """ - - name: Required[str] - """Required.""" - - -class InnerModel(TypedDict, total=False): - """Used in internal operations, should be generated but not exported. - - :ivar name: Required. - :vartype name: str - """ - - name: Required[str] - """Required.""" - - -class InternalDecoratorModelInInternal(TypedDict, total=False): - """Used in an internal operation, should be generated but not exported. - - :ivar name: Required. - :vartype name: str - """ - - name: Required[str] - """Required.""" - - -class NoDecoratorModelInInternal(TypedDict, total=False): - """Used in an internal operation, should be generated but not exported. - - :ivar name: Required. - :vartype name: str - """ - - name: Required[str] - """Required.""" - - -class NoDecoratorModelInPublic(TypedDict, total=False): - """Used in a public operation, should be generated and exported. - - :ivar name: Required. - :vartype name: str - """ - - name: Required[str] - """Required.""" - - -class OuterModel(BaseModel): - """Used in internal operations, should be generated but not exported. - - :ivar name: Required. - :vartype name: str - :ivar inner: Required. - :vartype inner: ~specs.azure.clientgenerator.core.access.models._models.InnerModel - """ - - inner: Required["InnerModel"] - """Required.""" - - -class PublicDecoratorModelInInternal(TypedDict, total=False): - """Used in an internal operation but with public decorator, should be generated and exported. - - :ivar name: Required. - :vartype name: str - """ - - name: Required[str] - """Required.""" - - -class PublicDecoratorModelInPublic(TypedDict, total=False): - """Used in a public operation, should be generated and exported. - - :ivar name: Required. - :vartype name: str - """ - - name: Required[str] - """Required.""" - - -class RealModel(TypedDict, total=False): - """Used in internal operations, should be generated but not exported. - - :ivar name: Required. - :vartype name: str - :ivar kind: Required. Default value is "real". - :vartype kind: str - """ - - name: Required[str] - """Required.""" - kind: Required[Literal["real"]] - """Required. Default value is \"real\".""" - - -class SharedModel(TypedDict, total=False): - """Used by both public and internal operation. It should be generated and exported. - - :ivar name: Required. - :vartype name: str - """ - - name: Required[str] - """Required.""" - - -AbstractModel = Union[RealModel] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/pyproject.toml index f2ab7b5fb6ef..ab2dff437051 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_utils/model_base.py index ec4b6303c4d8..44d55910f3b5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_utils/model_base.py @@ -112,6 +112,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -307,6 +330,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -336,6 +365,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -433,21 +466,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -457,7 +490,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -492,19 +525,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -517,10 +550,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -572,7 +606,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/operations/_operations.py index 48b1f770125b..b750a77032f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/operations/_operations.py @@ -28,7 +28,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -39,7 +39,6 @@ ) from .._configuration import AlternateTypeClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -244,11 +243,13 @@ async def put_property( """ @overload - async def put_property(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_property( + self, body: _types.ModelWithFeatureProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_property. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.alternatetype.types.ModelWithFeatureProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -272,12 +273,14 @@ async def put_property(self, body: IO[bytes], *, content_type: str = "applicatio """ @distributed_trace_async - async def put_property(self, body: Union[_models.ModelWithFeatureProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_property( + self, body: Union[_models.ModelWithFeatureProperty, _types.ModelWithFeatureProperty, IO[bytes]], **kwargs: Any + ) -> None: """put_property. - :param body: Is one of the following types: ModelWithFeatureProperty, JSON, IO[bytes] Required. + :param body: Is either a ModelWithFeatureProperty type or a IO[bytes] type. Required. :type body: ~specs.azure.clientgenerator.core.alternatetype.models.ModelWithFeatureProperty or - JSON or IO[bytes] + ~specs.azure.clientgenerator.core.alternatetype.types.ModelWithFeatureProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/models/_patch.py index 61a72371cd42..74cf0769bd70 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/models/_patch.py @@ -10,7 +10,6 @@ from typing import Type import geojson -from geojson.geometry import Geometry from .._utils.model_base import TYPE_HANDLER_REGISTRY @@ -42,7 +41,9 @@ def feature_deserializer(cls: Type[geojson.Feature], data: dict) -> geojson.Feat """ return cls( type=data.get("type"), - geometry=Geometry(type=data["geometry"].get("type"), coordinates=data["geometry"].get("coordinates")), + geometry=geojson.geometry.Geometry( # type: ignore + type=data["geometry"].get("type"), coordinates=data["geometry"].get("coordinates") + ), properties=data.get("properties"), id=data.get("id"), ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/operations/_operations.py index 66f62666be3b..e04114aec3a4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/operations/_operations.py @@ -28,12 +28,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import AlternateTypeClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -296,11 +295,13 @@ def put_property( """ @overload - def put_property(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_property( + self, body: _types.ModelWithFeatureProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_property. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.alternatetype.types.ModelWithFeatureProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -325,13 +326,13 @@ def put_property(self, body: IO[bytes], *, content_type: str = "application/json @distributed_trace def put_property( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ModelWithFeatureProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ModelWithFeatureProperty, _types.ModelWithFeatureProperty, IO[bytes]], **kwargs: Any ) -> None: """put_property. - :param body: Is one of the following types: ModelWithFeatureProperty, JSON, IO[bytes] Required. + :param body: Is either a ModelWithFeatureProperty type or a IO[bytes] type. Required. :type body: ~specs.azure.clientgenerator.core.alternatetype.models.ModelWithFeatureProperty or - JSON or IO[bytes] + ~specs.azure.clientgenerator.core.alternatetype.types.ModelWithFeatureProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/types.py index fc51867ea321..9e3c4d762f93 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-alternate-type/specs/azure/clientgenerator/core/alternatetype/types.py @@ -11,26 +11,11 @@ import geojson -class Geometry(TypedDict, total=False): - """Geometry. - - :ivar type: Required. - :vartype type: str - :ivar coordinates: Required. - :vartype coordinates: list[float] - """ - - type: Required[str] - """Required.""" - coordinates: Required[list[float]] - """Required.""" - - class ModelWithFeatureProperty(TypedDict, total=False): """ModelWithFeatureProperty. :ivar feature: Required. - :vartype feature: ~geojson.Feature + :vartype feature: geojson.Feature :ivar additional_property: Required. :vartype additional_property: str """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/client/alternateapiversion/service/header/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/pyproject.toml index f19913acee78..17c488390e1e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-header/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/client/alternateapiversion/service/path/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/pyproject.toml index 221880bd2b43..bbefa7703bb8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-path/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/client/alternateapiversion/service/query/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/pyproject.toml index a6e0f7c92ad3..aae5846a79c9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-api-version-query/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/pyproject.toml index 996faf4e29ac..ef4886e55ae8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_operations/_operations.py index d00ea128d15c..630f5cafc486 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import ClientDefaultValueClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -133,12 +132,12 @@ def put_model_property( @overload def put_model_property( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelWithDefaultValues, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelWithDefaultValues: """put_model_property. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.clientdefaultvalue.types.ModelWithDefaultValues :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -165,13 +164,14 @@ def put_model_property( @distributed_trace def put_model_property( - self, body: Union[_models.ModelWithDefaultValues, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ModelWithDefaultValues, _types.ModelWithDefaultValues, IO[bytes]], **kwargs: Any ) -> _models.ModelWithDefaultValues: """put_model_property. - :param body: Is one of the following types: ModelWithDefaultValues, JSON, IO[bytes] Required. + :param body: Is either a ModelWithDefaultValues type or a IO[bytes] type. Required. :type body: ~specs.azure.clientgenerator.core.clientdefaultvalue.models.ModelWithDefaultValues - or JSON or IO[bytes] + or ~specs.azure.clientgenerator.core.clientdefaultvalue.types.ModelWithDefaultValues or + IO[bytes] :return: ModelWithDefaultValues. The ModelWithDefaultValues is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.clientdefaultvalue.models.ModelWithDefaultValues :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_operations/_operations.py index efca8472e760..a629fdc2fda6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_client_default_value_get_header_parameter_request, build_client_default_value_get_operation_parameter_request, @@ -38,7 +38,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import ClientDefaultValueClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -65,12 +64,12 @@ async def put_model_property( @overload async def put_model_property( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelWithDefaultValues, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelWithDefaultValues: """put_model_property. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.clientdefaultvalue.types.ModelWithDefaultValues :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -97,13 +96,14 @@ async def put_model_property( @distributed_trace_async async def put_model_property( - self, body: Union[_models.ModelWithDefaultValues, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ModelWithDefaultValues, _types.ModelWithDefaultValues, IO[bytes]], **kwargs: Any ) -> _models.ModelWithDefaultValues: """put_model_property. - :param body: Is one of the following types: ModelWithDefaultValues, JSON, IO[bytes] Required. + :param body: Is either a ModelWithDefaultValues type or a IO[bytes] type. Required. :type body: ~specs.azure.clientgenerator.core.clientdefaultvalue.models.ModelWithDefaultValues - or JSON or IO[bytes] + or ~specs.azure.clientgenerator.core.clientdefaultvalue.types.ModelWithDefaultValues or + IO[bytes] :return: ModelWithDefaultValues. The ModelWithDefaultValues is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.clientdefaultvalue.models.ModelWithDefaultValues :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-default-value/specs/azure/clientgenerator/core/clientdefaultvalue/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/pyproject.toml index 7508ede5df51..d93ac6444c78 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/operations/_operations.py index 326617ccd058..2a6b4306974a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import build_documentation_harvest_request from .._configuration import ClientDocClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -71,11 +70,13 @@ async def harvest( """ @overload - async def harvest(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Plant: + async def harvest( + self, body: _types.Plant, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Plant: """Retrieves a plant from the garden by submitting its name. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.clientdoc.types.Plant :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -99,11 +100,12 @@ async def harvest(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def harvest(self, body: Union[_models.Plant, JSON, IO[bytes]], **kwargs: Any) -> _models.Plant: + async def harvest(self, body: Union[_models.Plant, _types.Plant, IO[bytes]], **kwargs: Any) -> _models.Plant: """Retrieves a plant from the garden by submitting its name. - :param body: Is one of the following types: Plant, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientdoc.models.Plant or JSON or IO[bytes] + :param body: Is either a Plant type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.clientdoc.models.Plant or + ~specs.azure.clientgenerator.core.clientdoc.types.Plant or IO[bytes] :return: Plant. The Plant is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.clientdoc.models.Plant :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/operations/_operations.py index 8544e2577414..000f651f8b51 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import ClientDocClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -88,11 +87,11 @@ def harvest(self, body: _models.Plant, *, content_type: str = "application/json" """ @overload - def harvest(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Plant: + def harvest(self, body: _types.Plant, *, content_type: str = "application/json", **kwargs: Any) -> _models.Plant: """Retrieves a plant from the garden by submitting its name. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.clientdoc.types.Plant :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -116,11 +115,12 @@ def harvest(self, body: IO[bytes], *, content_type: str = "application/json", ** """ @distributed_trace - def harvest(self, body: Union[_models.Plant, JSON, IO[bytes]], **kwargs: Any) -> _models.Plant: + def harvest(self, body: Union[_models.Plant, _types.Plant, IO[bytes]], **kwargs: Any) -> _models.Plant: """Retrieves a plant from the garden by submitting its name. - :param body: Is one of the following types: Plant, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientdoc.models.Plant or JSON or IO[bytes] + :param body: Is either a Plant type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.clientdoc.models.Plant or + ~specs.azure.clientgenerator.core.clientdoc.types.Plant or IO[bytes] :return: Plant. The Plant is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.clientdoc.models.Plant :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-doc/specs/azure/clientgenerator/core/clientdoc/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/pyproject.toml index 928f1dfc351e..faeb0628dd1b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_operations/_operations.py index e2b86286d54b..edc09fdc76d1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import ( HeaderParamClientConfiguration, MixedParamsClientConfiguration, @@ -40,7 +40,6 @@ from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -343,11 +342,11 @@ def with_body(self, body: _models.Input, *, content_type: str = "application/jso """ @overload - def with_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_body(self, body: _types.Input, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_body. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.types.Input :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -372,13 +371,13 @@ def with_body(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_body( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.Input, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.Input, _types.Input, IO[bytes]], **kwargs: Any ) -> None: """with_body. - :param body: Is one of the following types: Input, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.models.Input or JSON - or IO[bytes] + :param body: Is either a Input type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.models.Input or + ~specs.azure.clientgenerator.core.clientinitialization.default.types.Input or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -499,11 +498,11 @@ def with_body(self, body: _models.Input, *, content_type: str = "application/jso """ @overload - def with_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_body(self, body: _types.Input, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_body. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.types.Input :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -528,13 +527,13 @@ def with_body(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_body( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.Input, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.Input, _types.Input, IO[bytes]], **kwargs: Any ) -> None: """with_body. - :param body: Is one of the following types: Input, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.models.Input or JSON - or IO[bytes] + :param body: Is either a Input type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.models.Input or + ~specs.azure.clientgenerator.core.clientinitialization.default.types.Input or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -665,11 +664,14 @@ def with_body( """ @overload - def with_body(self, body: JSON, *, region: str, content_type: str = "application/json", **kwargs: Any) -> None: + def with_body( + self, body: _types.WithBodyRequest, *, region: str, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_body. :param body: Required. - :type body: JSON + :type body: + ~specs.azure.clientgenerator.core.clientinitialization.default.types.WithBodyRequest :keyword region: Required. :paramtype region: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -698,14 +700,15 @@ def with_body(self, body: IO[bytes], *, region: str, content_type: str = "applic @distributed_trace def with_body( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.WithBodyRequest, JSON, IO[bytes]], *, region: str, **kwargs: Any + self, body: Union[_models.WithBodyRequest, _types.WithBodyRequest, IO[bytes]], *, region: str, **kwargs: Any ) -> None: """with_body. - :param body: Is one of the following types: WithBodyRequest, JSON, IO[bytes] Required. + :param body: Is either a WithBodyRequest type or a IO[bytes] type. Required. :type body: - ~specs.azure.clientgenerator.core.clientinitialization.default.models.WithBodyRequest or JSON - or IO[bytes] + ~specs.azure.clientgenerator.core.clientinitialization.default.models.WithBodyRequest or + ~specs.azure.clientgenerator.core.clientinitialization.default.types.WithBodyRequest or + IO[bytes] :keyword region: Required. :paramtype region: str :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_operations/_operations.py index 7b479ff00a22..f4004d4e7d19 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_header_param_with_body_request, build_header_param_with_query_request, @@ -55,7 +55,6 @@ QueryParamClientConfiguration, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -127,11 +126,11 @@ async def with_body(self, body: _models.Input, *, content_type: str = "applicati """ @overload - async def with_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_body(self, body: _types.Input, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_body. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.types.Input :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -155,12 +154,12 @@ async def with_body(self, body: IO[bytes], *, content_type: str = "application/j """ @distributed_trace_async - async def with_body(self, body: Union[_models.Input, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_body(self, body: Union[_models.Input, _types.Input, IO[bytes]], **kwargs: Any) -> None: """with_body. - :param body: Is one of the following types: Input, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.models.Input or JSON - or IO[bytes] + :param body: Is either a Input type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.models.Input or + ~specs.azure.clientgenerator.core.clientinitialization.default.types.Input or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -281,11 +280,11 @@ async def with_body(self, body: _models.Input, *, content_type: str = "applicati """ @overload - async def with_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_body(self, body: _types.Input, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_body. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.types.Input :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -309,12 +308,12 @@ async def with_body(self, body: IO[bytes], *, content_type: str = "application/j """ @distributed_trace_async - async def with_body(self, body: Union[_models.Input, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_body(self, body: Union[_models.Input, _types.Input, IO[bytes]], **kwargs: Any) -> None: """with_body. - :param body: Is one of the following types: Input, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.models.Input or JSON - or IO[bytes] + :param body: Is either a Input type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.clientinitialization.default.models.Input or + ~specs.azure.clientgenerator.core.clientinitialization.default.types.Input or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -444,12 +443,13 @@ async def with_body( @overload async def with_body( - self, body: JSON, *, region: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.WithBodyRequest, *, region: str, content_type: str = "application/json", **kwargs: Any ) -> None: """with_body. :param body: Required. - :type body: JSON + :type body: + ~specs.azure.clientgenerator.core.clientinitialization.default.types.WithBodyRequest :keyword region: Required. :paramtype region: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -480,14 +480,15 @@ async def with_body( @distributed_trace_async async def with_body( - self, body: Union[_models.WithBodyRequest, JSON, IO[bytes]], *, region: str, **kwargs: Any + self, body: Union[_models.WithBodyRequest, _types.WithBodyRequest, IO[bytes]], *, region: str, **kwargs: Any ) -> None: """with_body. - :param body: Is one of the following types: WithBodyRequest, JSON, IO[bytes] Required. + :param body: Is either a WithBodyRequest type or a IO[bytes] type. Required. :type body: - ~specs.azure.clientgenerator.core.clientinitialization.default.models.WithBodyRequest or JSON - or IO[bytes] + ~specs.azure.clientgenerator.core.clientinitialization.default.models.WithBodyRequest or + ~specs.azure.clientgenerator.core.clientinitialization.default.types.WithBodyRequest or + IO[bytes] :keyword region: Required. :paramtype region: str :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/types.py index e21bdf2e9adb..e4aead5fb51a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-default/specs/azure/clientgenerator/core/clientinitialization/default/types.py @@ -6,33 +6,9 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime from typing_extensions import Required, TypedDict -class BlobProperties(TypedDict, total=False): - """Properties of a blob. - - :ivar name: Required. - :vartype name: str - :ivar size: Required. - :vartype size: int - :ivar content_type: Required. - :vartype content_type: str - :ivar created_on: Required. - :vartype created_on: ~datetime.datetime - """ - - name: Required[str] - """Required.""" - size: Required[int] - """Required.""" - contentType: Required[str] - """Required.""" - createdOn: Required[datetime.datetime] - """Required.""" - - class Input(TypedDict, total=False): """Input. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/pyproject.toml index 4bb4f486599f..cedcd52c05e8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/types.py deleted file mode 100644 index a555e5854a41..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individually/specs/azure/clientgenerator/core/clientinitialization/individually/types.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing_extensions import Required, TypedDict - - -class BlobProperties(TypedDict, total=False): - """Properties of a blob. - - :ivar name: Required. - :vartype name: str - :ivar size: Required. - :vartype size: int - :ivar content_type: Required. - :vartype content_type: str - :ivar created_on: Required. - :vartype created_on: ~datetime.datetime - """ - - name: Required[str] - """Required.""" - size: Required[int] - """Required.""" - contentType: Required[str] - """Required.""" - createdOn: Required[datetime.datetime] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/pyproject.toml index 7b9b2f6c5cec..edfac5ea9f52 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/types.py deleted file mode 100644 index a555e5854a41..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization-individuallyparent/specs/azure/clientgenerator/core/clientinitialization/individuallyparent/types.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing_extensions import Required, TypedDict - - -class BlobProperties(TypedDict, total=False): - """Properties of a blob. - - :ivar name: Required. - :vartype name: str - :ivar size: Required. - :vartype size: int - :ivar content_type: Required. - :vartype content_type: str - :ivar created_on: Required. - :vartype created_on: ~datetime.datetime - """ - - name: Required[str] - """Required.""" - size: Required[int] - """Required.""" - contentType: Required[str] - """Required.""" - createdOn: Required[datetime.datetime] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/apiview-properties.json deleted file mode 100644 index bc22379471ff..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/apiview-properties.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "CrossLanguagePackageId": "Service", - "CrossLanguageDefinitionId": { - "specs.azure.clientgenerator.core.clientinitialization.models.BlobProperties": "Service.BlobProperties", - "specs.azure.clientgenerator.core.clientinitialization.models.Input": "Service.Input", - "specs.azure.clientgenerator.core.clientinitialization.models.WithBodyRequest": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.withBody.Request.anonymous", - "specs.azure.clientgenerator.core.clientinitialization.HeaderParamClient.with_query": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.HeaderParam.withQuery", - "specs.azure.clientgenerator.core.clientinitialization.aio.HeaderParamClient.with_query": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.HeaderParam.withQuery", - "specs.azure.clientgenerator.core.clientinitialization.HeaderParamClient.with_body": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.HeaderParam.withBody", - "specs.azure.clientgenerator.core.clientinitialization.aio.HeaderParamClient.with_body": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.HeaderParam.withBody", - "specs.azure.clientgenerator.core.clientinitialization.MultipleParamsClient.with_query": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.MultipleParams.withQuery", - "specs.azure.clientgenerator.core.clientinitialization.aio.MultipleParamsClient.with_query": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.MultipleParams.withQuery", - "specs.azure.clientgenerator.core.clientinitialization.MultipleParamsClient.with_body": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.MultipleParams.withBody", - "specs.azure.clientgenerator.core.clientinitialization.aio.MultipleParamsClient.with_body": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.MultipleParams.withBody", - "specs.azure.clientgenerator.core.clientinitialization.MixedParamsClient.with_query": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.MixedParams.withQuery", - "specs.azure.clientgenerator.core.clientinitialization.aio.MixedParamsClient.with_query": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.MixedParams.withQuery", - "specs.azure.clientgenerator.core.clientinitialization.MixedParamsClient.with_body": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.MixedParams.withBody", - "specs.azure.clientgenerator.core.clientinitialization.aio.MixedParamsClient.with_body": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.MixedParams.withBody", - "specs.azure.clientgenerator.core.clientinitialization.PathParamClient.with_query": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.PathParam.withQuery", - "specs.azure.clientgenerator.core.clientinitialization.aio.PathParamClient.with_query": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.PathParam.withQuery", - "specs.azure.clientgenerator.core.clientinitialization.PathParamClient.get_standalone": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.PathParam.getStandalone", - "specs.azure.clientgenerator.core.clientinitialization.aio.PathParamClient.get_standalone": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.PathParam.getStandalone", - "specs.azure.clientgenerator.core.clientinitialization.PathParamClient.delete_standalone": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.PathParam.deleteStandalone", - "specs.azure.clientgenerator.core.clientinitialization.aio.PathParamClient.delete_standalone": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.PathParam.deleteStandalone", - "specs.azure.clientgenerator.core.clientinitialization.ParamAliasClient.with_aliased_name": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.ParamAlias.withAliasedName", - "specs.azure.clientgenerator.core.clientinitialization.aio.ParamAliasClient.with_aliased_name": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.ParamAlias.withAliasedName", - "specs.azure.clientgenerator.core.clientinitialization.ParamAliasClient.with_original_name": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.ParamAlias.withOriginalName", - "specs.azure.clientgenerator.core.clientinitialization.aio.ParamAliasClient.with_original_name": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.ParamAlias.withOriginalName", - "specs.azure.clientgenerator.core.clientinitialization.operations.ChildClientOperations.with_query": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.ParentClient.ChildClient.withQuery", - "specs.azure.clientgenerator.core.clientinitialization.aio.operations.ChildClientOperations.with_query": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.ParentClient.ChildClient.withQuery", - "specs.azure.clientgenerator.core.clientinitialization.operations.ChildClientOperations.get_standalone": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.ParentClient.ChildClient.getStandalone", - "specs.azure.clientgenerator.core.clientinitialization.aio.operations.ChildClientOperations.get_standalone": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.ParentClient.ChildClient.getStandalone", - "specs.azure.clientgenerator.core.clientinitialization.operations.ChildClientOperations.delete_standalone": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.ParentClient.ChildClient.deleteStandalone", - "specs.azure.clientgenerator.core.clientinitialization.aio.operations.ChildClientOperations.delete_standalone": "_Specs_.Azure.ClientGenerator.Core.ClientInitialization.ParentClient.ChildClient.deleteStandalone" - } -} \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/conftest.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/conftest.py deleted file mode 100644 index 7c1d5cc6a53a..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/conftest.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import os -import pytest -from dotenv import load_dotenv -from devtools_testutils import ( - test_proxy, - add_general_regex_sanitizer, - add_body_key_sanitizer, - add_header_regex_sanitizer, -) - -load_dotenv() - - -# For security, please avoid record sensitive identity information in recordings -@pytest.fixture(scope="session", autouse=True) -def add_sanitizers(test_proxy): - headerparam_subscription_id = os.environ.get("HEADERPARAM_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") - headerparam_tenant_id = os.environ.get("HEADERPARAM_TENANT_ID", "00000000-0000-0000-0000-000000000000") - headerparam_client_id = os.environ.get("HEADERPARAM_CLIENT_ID", "00000000-0000-0000-0000-000000000000") - headerparam_client_secret = os.environ.get("HEADERPARAM_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=headerparam_subscription_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=headerparam_tenant_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=headerparam_client_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=headerparam_client_secret, value="00000000-0000-0000-0000-000000000000") - - multipleparams_subscription_id = os.environ.get( - "MULTIPLEPARAMS_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" - ) - multipleparams_tenant_id = os.environ.get("MULTIPLEPARAMS_TENANT_ID", "00000000-0000-0000-0000-000000000000") - multipleparams_client_id = os.environ.get("MULTIPLEPARAMS_CLIENT_ID", "00000000-0000-0000-0000-000000000000") - multipleparams_client_secret = os.environ.get( - "MULTIPLEPARAMS_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" - ) - add_general_regex_sanitizer(regex=multipleparams_subscription_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=multipleparams_tenant_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=multipleparams_client_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=multipleparams_client_secret, value="00000000-0000-0000-0000-000000000000") - - mixedparams_subscription_id = os.environ.get("MIXEDPARAMS_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") - mixedparams_tenant_id = os.environ.get("MIXEDPARAMS_TENANT_ID", "00000000-0000-0000-0000-000000000000") - mixedparams_client_id = os.environ.get("MIXEDPARAMS_CLIENT_ID", "00000000-0000-0000-0000-000000000000") - mixedparams_client_secret = os.environ.get("MIXEDPARAMS_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=mixedparams_subscription_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=mixedparams_tenant_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=mixedparams_client_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=mixedparams_client_secret, value="00000000-0000-0000-0000-000000000000") - - pathparam_subscription_id = os.environ.get("PATHPARAM_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") - pathparam_tenant_id = os.environ.get("PATHPARAM_TENANT_ID", "00000000-0000-0000-0000-000000000000") - pathparam_client_id = os.environ.get("PATHPARAM_CLIENT_ID", "00000000-0000-0000-0000-000000000000") - pathparam_client_secret = os.environ.get("PATHPARAM_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=pathparam_subscription_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=pathparam_tenant_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=pathparam_client_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=pathparam_client_secret, value="00000000-0000-0000-0000-000000000000") - - paramalias_subscription_id = os.environ.get("PARAMALIAS_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") - paramalias_tenant_id = os.environ.get("PARAMALIAS_TENANT_ID", "00000000-0000-0000-0000-000000000000") - paramalias_client_id = os.environ.get("PARAMALIAS_CLIENT_ID", "00000000-0000-0000-0000-000000000000") - paramalias_client_secret = os.environ.get("PARAMALIAS_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=paramalias_subscription_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=paramalias_tenant_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=paramalias_client_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=paramalias_client_secret, value="00000000-0000-0000-0000-000000000000") - - parent_subscription_id = os.environ.get("PARENT_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") - parent_tenant_id = os.environ.get("PARENT_TENANT_ID", "00000000-0000-0000-0000-000000000000") - parent_client_id = os.environ.get("PARENT_CLIENT_ID", "00000000-0000-0000-0000-000000000000") - parent_client_secret = os.environ.get("PARENT_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=parent_subscription_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=parent_tenant_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=parent_client_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=parent_client_secret, value="00000000-0000-0000-0000-000000000000") - - add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") - add_header_regex_sanitizer(key="Cookie", value="cookie;") - add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_mixed_params_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_mixed_params_async.py deleted file mode 100644 index 9e962339c9e7..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_mixed_params_async.py +++ /dev/null @@ -1,38 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from devtools_testutils.aio import recorded_by_proxy_async -from testpreparer import MixedParamsPreparer -from testpreparer_async import MixedParamsClientTestBaseAsync - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestMixedParamsAsync(MixedParamsClientTestBaseAsync): - @MixedParamsPreparer() - @recorded_by_proxy_async - async def test_with_query(self, mixedparams_endpoint): - client = self.create_async_client(endpoint=mixedparams_endpoint) - response = await client.with_query( - region="str", - id="str", - ) - - # please add some check logic here by yourself - # ... - - @MixedParamsPreparer() - @recorded_by_proxy_async - async def test_with_body(self, mixedparams_endpoint): - client = self.create_async_client(endpoint=mixedparams_endpoint) - response = await client.with_body( - body={"name": "str"}, - region="str", - ) - - # please add some check logic here by yourself - # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_parent_child_client_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_parent_child_client_operations.py deleted file mode 100644 index edef34518f2e..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_parent_child_client_operations.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from devtools_testutils import recorded_by_proxy -from testpreparer import ParentClientTestBase, ParentPreparer - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestParentChildClientOperations(ParentClientTestBase): - @ParentPreparer() - @recorded_by_proxy - def test_child_client_with_query(self, parent_endpoint): - client = self.create_client(endpoint=parent_endpoint) - response = client.child_client.with_query() - - # please add some check logic here by yourself - # ... - - @ParentPreparer() - @recorded_by_proxy - def test_child_client_get_standalone(self, parent_endpoint): - client = self.create_client(endpoint=parent_endpoint) - response = client.child_client.get_standalone() - - # please add some check logic here by yourself - # ... - - @ParentPreparer() - @recorded_by_proxy - def test_child_client_delete_standalone(self, parent_endpoint): - client = self.create_client(endpoint=parent_endpoint) - response = client.child_client.delete_standalone() - - # please add some check logic here by yourself - # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_parent_child_client_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_parent_child_client_operations_async.py deleted file mode 100644 index 60bf21dee4ec..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_parent_child_client_operations_async.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from devtools_testutils.aio import recorded_by_proxy_async -from testpreparer import ParentPreparer -from testpreparer_async import ParentClientTestBaseAsync - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestParentChildClientOperationsAsync(ParentClientTestBaseAsync): - @ParentPreparer() - @recorded_by_proxy_async - async def test_child_client_with_query(self, parent_endpoint): - client = self.create_async_client(endpoint=parent_endpoint) - response = await client.child_client.with_query() - - # please add some check logic here by yourself - # ... - - @ParentPreparer() - @recorded_by_proxy_async - async def test_child_client_get_standalone(self, parent_endpoint): - client = self.create_async_client(endpoint=parent_endpoint) - response = await client.child_client.get_standalone() - - # please add some check logic here by yourself - # ... - - @ParentPreparer() - @recorded_by_proxy_async - async def test_child_client_delete_standalone(self, parent_endpoint): - client = self.create_async_client(endpoint=parent_endpoint) - response = await client.child_client.delete_standalone() - - # please add some check logic here by yourself - # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_path_param.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_path_param.py deleted file mode 100644 index 66aa7f93817c..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_path_param.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from devtools_testutils import recorded_by_proxy -from testpreparer import PathParamClientTestBase, PathParamPreparer - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPathParam(PathParamClientTestBase): - @PathParamPreparer() - @recorded_by_proxy - def test_with_query(self, pathparam_endpoint): - client = self.create_client(endpoint=pathparam_endpoint) - response = client.with_query() - - # please add some check logic here by yourself - # ... - - @PathParamPreparer() - @recorded_by_proxy - def test_get_standalone(self, pathparam_endpoint): - client = self.create_client(endpoint=pathparam_endpoint) - response = client.get_standalone() - - # please add some check logic here by yourself - # ... - - @PathParamPreparer() - @recorded_by_proxy - def test_delete_standalone(self, pathparam_endpoint): - client = self.create_client(endpoint=pathparam_endpoint) - response = client.delete_standalone() - - # please add some check logic here by yourself - # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_path_param_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_path_param_async.py deleted file mode 100644 index 43c3d4ebed88..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_path_param_async.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from devtools_testutils.aio import recorded_by_proxy_async -from testpreparer import PathParamPreparer -from testpreparer_async import PathParamClientTestBaseAsync - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestPathParamAsync(PathParamClientTestBaseAsync): - @PathParamPreparer() - @recorded_by_proxy_async - async def test_with_query(self, pathparam_endpoint): - client = self.create_async_client(endpoint=pathparam_endpoint) - response = await client.with_query() - - # please add some check logic here by yourself - # ... - - @PathParamPreparer() - @recorded_by_proxy_async - async def test_get_standalone(self, pathparam_endpoint): - client = self.create_async_client(endpoint=pathparam_endpoint) - response = await client.get_standalone() - - # please add some check logic here by yourself - # ... - - @PathParamPreparer() - @recorded_by_proxy_async - async def test_delete_standalone(self, pathparam_endpoint): - client = self.create_async_client(endpoint=pathparam_endpoint) - response = await client.delete_standalone() - - # please add some check logic here by yourself - # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/testpreparer.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/testpreparer.py deleted file mode 100644 index dc2403a0d5a7..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/testpreparer.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer -import functools -from specs.azure.clientgenerator.core.clientinitialization import ( - HeaderParamClient, - MixedParamsClient, - MultipleParamsClient, - ParamAliasClient, - ParentClient, - PathParamClient, -) - - -class HeaderParamClientTestBase(AzureRecordedTestCase): - - def create_client(self, endpoint): - credential = self.get_credential(HeaderParamClient) - return self.create_client_from_credential( - HeaderParamClient, - credential=credential, - endpoint=endpoint, - ) - - -HeaderParamPreparer = functools.partial( - PowerShellPreparer, "headerparam", headerparam_endpoint="https://fake_headerparam_endpoint.com" -) - - -class MultipleParamsClientTestBase(AzureRecordedTestCase): - - def create_client(self, endpoint): - credential = self.get_credential(MultipleParamsClient) - return self.create_client_from_credential( - MultipleParamsClient, - credential=credential, - endpoint=endpoint, - ) - - -MultipleParamsPreparer = functools.partial( - PowerShellPreparer, "multipleparams", multipleparams_endpoint="https://fake_multipleparams_endpoint.com" -) - - -class MixedParamsClientTestBase(AzureRecordedTestCase): - - def create_client(self, endpoint): - credential = self.get_credential(MixedParamsClient) - return self.create_client_from_credential( - MixedParamsClient, - credential=credential, - endpoint=endpoint, - ) - - -MixedParamsPreparer = functools.partial( - PowerShellPreparer, "mixedparams", mixedparams_endpoint="https://fake_mixedparams_endpoint.com" -) - - -class PathParamClientTestBase(AzureRecordedTestCase): - - def create_client(self, endpoint): - credential = self.get_credential(PathParamClient) - return self.create_client_from_credential( - PathParamClient, - credential=credential, - endpoint=endpoint, - ) - - -PathParamPreparer = functools.partial( - PowerShellPreparer, "pathparam", pathparam_endpoint="https://fake_pathparam_endpoint.com" -) - - -class ParamAliasClientTestBase(AzureRecordedTestCase): - - def create_client(self, endpoint): - credential = self.get_credential(ParamAliasClient) - return self.create_client_from_credential( - ParamAliasClient, - credential=credential, - endpoint=endpoint, - ) - - -ParamAliasPreparer = functools.partial( - PowerShellPreparer, "paramalias", paramalias_endpoint="https://fake_paramalias_endpoint.com" -) - - -class ParentClientTestBase(AzureRecordedTestCase): - - def create_client(self, endpoint): - credential = self.get_credential(ParentClient) - return self.create_client_from_credential( - ParentClient, - credential=credential, - endpoint=endpoint, - ) - - -ParentPreparer = functools.partial(PowerShellPreparer, "parent", parent_endpoint="https://fake_parent_endpoint.com") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/testpreparer_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/testpreparer_async.py deleted file mode 100644 index 2c374ca8de23..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/testpreparer_async.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from devtools_testutils import AzureRecordedTestCase -from specs.azure.clientgenerator.core.clientinitialization.aio import ( - HeaderParamClient, - MixedParamsClient, - MultipleParamsClient, - ParamAliasClient, - ParentClient, - PathParamClient, -) - - -class HeaderParamClientTestBaseAsync(AzureRecordedTestCase): - - def create_async_client(self, endpoint): - credential = self.get_credential(HeaderParamClient, is_async=True) - return self.create_client_from_credential( - HeaderParamClient, - credential=credential, - endpoint=endpoint, - ) - - -class MultipleParamsClientTestBaseAsync(AzureRecordedTestCase): - - def create_async_client(self, endpoint): - credential = self.get_credential(MultipleParamsClient, is_async=True) - return self.create_client_from_credential( - MultipleParamsClient, - credential=credential, - endpoint=endpoint, - ) - - -class MixedParamsClientTestBaseAsync(AzureRecordedTestCase): - - def create_async_client(self, endpoint): - credential = self.get_credential(MixedParamsClient, is_async=True) - return self.create_client_from_credential( - MixedParamsClient, - credential=credential, - endpoint=endpoint, - ) - - -class PathParamClientTestBaseAsync(AzureRecordedTestCase): - - def create_async_client(self, endpoint): - credential = self.get_credential(PathParamClient, is_async=True) - return self.create_client_from_credential( - PathParamClient, - credential=credential, - endpoint=endpoint, - ) - - -class ParamAliasClientTestBaseAsync(AzureRecordedTestCase): - - def create_async_client(self, endpoint): - credential = self.get_credential(ParamAliasClient, is_async=True) - return self.create_client_from_credential( - ParamAliasClient, - credential=credential, - endpoint=endpoint, - ) - - -class ParentClientTestBaseAsync(AzureRecordedTestCase): - - def create_async_client(self, endpoint): - credential = self.get_credential(ParentClient, is_async=True) - return self.create_client_from_credential( - ParentClient, - credential=credential, - endpoint=endpoint, - ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/__init__.py deleted file mode 100644 index 979b2e24d000..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._client import HeaderParamClient # type: ignore -from ._client import MultipleParamsClient # type: ignore -from ._client import MixedParamsClient # type: ignore -from ._client import PathParamClient # type: ignore -from ._client import ParamAliasClient # type: ignore -from ._client import ParentClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "HeaderParamClient", - "MultipleParamsClient", - "MixedParamsClient", - "PathParamClient", - "ParamAliasClient", - "ParentClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_client.py deleted file mode 100644 index 7223ce139dca..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_client.py +++ /dev/null @@ -1,495 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any -from typing_extensions import Self - -from azure.core import PipelineClient -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import ( - HeaderParamClientConfiguration, - MixedParamsClientConfiguration, - MultipleParamsClientConfiguration, - ParamAliasClientConfiguration, - ParentClientConfiguration, - PathParamClientConfiguration, -) -from ._utils.serialization import Deserializer, Serializer -from .operations import ( - ChildClientOperations, - _HeaderParamClientOperationsMixin, - _MixedParamsClientOperationsMixin, - _MultipleParamsClientOperationsMixin, - _ParamAliasClientOperationsMixin, - _PathParamClientOperationsMixin, -) - - -class HeaderParamClient(_HeaderParamClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """Client for testing header parameter moved to client level. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, name: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = HeaderParamClientConfiguration(name=name, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) - - -class MultipleParamsClient(_MultipleParamsClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """MultipleParamsClient. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :param region: The region to use for all operations. This parameter is used as a query - parameter. Required. - :type region: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, name: str, region: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = MultipleParamsClientConfiguration(name=name, region=region, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) - - -class MixedParamsClient(_MixedParamsClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """MixedParamsClient. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, name: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = MixedParamsClientConfiguration(name=name, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) - - -class PathParamClient(_PathParamClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """PathParamClient. - - :param blob_name: The name of the blob. This parameter is used as a path parameter in all - operations. Required. - :type blob_name: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, blob_name: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = PathParamClientConfiguration(blob_name=blob_name, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) - - -class ParamAliasClient(_ParamAliasClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """ParamAliasClient. - - :param blob_name: Blob name for the client. Required. - :type blob_name: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, blob_name: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = ParamAliasClientConfiguration(blob_name=blob_name, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) - - -class ParentClient: # pylint: disable=client-accepts-api-version-keyword - """ParentClient. - - :ivar child_client: ChildClientOperations operations - :vartype child_client: - specs.azure.clientgenerator.core.clientinitialization.operations.ChildClientOperations - :param blob_name: The name of the blob. This parameter is used as a path parameter in all - operations. Required. - :type blob_name: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, blob_name: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = ParentClientConfiguration(blob_name=blob_name, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - self.child_client = ChildClientOperations(self._client, self._config, self._serialize, self._deserialize) - - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_configuration.py deleted file mode 100644 index 56d0d7a38f2c..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_configuration.py +++ /dev/null @@ -1,228 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -from ._version import VERSION - - -class HeaderParamClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for HeaderParamClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, name: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if name is None: - raise ValueError("Parameter 'name' must not be None.") - - self.name = name - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - - -class MultipleParamsClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for MultipleParamsClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :param region: The region to use for all operations. This parameter is used as a query - parameter. Required. - :type region: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, name: str, region: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if name is None: - raise ValueError("Parameter 'name' must not be None.") - if region is None: - raise ValueError("Parameter 'region' must not be None.") - - self.name = name - self.region = region - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - - -class MixedParamsClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for MixedParamsClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, name: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if name is None: - raise ValueError("Parameter 'name' must not be None.") - - self.name = name - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - - -class PathParamClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for PathParamClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param blob_name: The name of the blob. This parameter is used as a path parameter in all - operations. Required. - :type blob_name: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, blob_name: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if blob_name is None: - raise ValueError("Parameter 'blob_name' must not be None.") - - self.blob_name = blob_name - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - - -class ParamAliasClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ParamAliasClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param blob_name: Blob name for the client. Required. - :type blob_name: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, blob_name: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if blob_name is None: - raise ValueError("Parameter 'blob_name' must not be None.") - - self.blob_name = blob_name - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - - -class ParentClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ParentClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param blob_name: The name of the blob. This parameter is used as a path parameter in all - operations. Required. - :type blob_name: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, blob_name: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if blob_name is None: - raise ValueError("Parameter 'blob_name' must not be None.") - - self.blob_name = blob_name - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/__init__.py deleted file mode 100644 index b3e6701bb3a5..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._client import HeaderParamClient # type: ignore -from ._client import MultipleParamsClient # type: ignore -from ._client import MixedParamsClient # type: ignore -from ._client import PathParamClient # type: ignore -from ._client import ParamAliasClient # type: ignore -from ._client import ParentClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "HeaderParamClient", - "MultipleParamsClient", - "MixedParamsClient", - "PathParamClient", - "ParamAliasClient", - "ParentClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/_client.py deleted file mode 100644 index f0639c614360..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/_client.py +++ /dev/null @@ -1,507 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable -from typing_extensions import Self - -from azure.core import AsyncPipelineClient -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._utils.serialization import Deserializer, Serializer -from ._configuration import ( - HeaderParamClientConfiguration, - MixedParamsClientConfiguration, - MultipleParamsClientConfiguration, - ParamAliasClientConfiguration, - ParentClientConfiguration, - PathParamClientConfiguration, -) -from .operations import ( - ChildClientOperations, - _HeaderParamClientOperationsMixin, - _MixedParamsClientOperationsMixin, - _MultipleParamsClientOperationsMixin, - _ParamAliasClientOperationsMixin, - _PathParamClientOperationsMixin, -) - - -class HeaderParamClient(_HeaderParamClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """Client for testing header parameter moved to client level. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, name: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = HeaderParamClientConfiguration(name=name, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) - - -class MultipleParamsClient(_MultipleParamsClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """MultipleParamsClient. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :param region: The region to use for all operations. This parameter is used as a query - parameter. Required. - :type region: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, name: str, region: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = MultipleParamsClientConfiguration(name=name, region=region, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) - - -class MixedParamsClient(_MixedParamsClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """MixedParamsClient. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, name: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = MixedParamsClientConfiguration(name=name, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) - - -class PathParamClient(_PathParamClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """PathParamClient. - - :param blob_name: The name of the blob. This parameter is used as a path parameter in all - operations. Required. - :type blob_name: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, blob_name: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = PathParamClientConfiguration(blob_name=blob_name, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) - - -class ParamAliasClient(_ParamAliasClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """ParamAliasClient. - - :param blob_name: Blob name for the client. Required. - :type blob_name: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, blob_name: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = ParamAliasClientConfiguration(blob_name=blob_name, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) - - -class ParentClient: # pylint: disable=client-accepts-api-version-keyword - """ParentClient. - - :ivar child_client: ChildClientOperations operations - :vartype child_client: - specs.azure.clientgenerator.core.clientinitialization.aio.operations.ChildClientOperations - :param blob_name: The name of the blob. This parameter is used as a path parameter in all - operations. Required. - :type blob_name: str - :keyword endpoint: Service host. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, blob_name: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - _endpoint = "{endpoint}" - self._config = ParentClientConfiguration(blob_name=blob_name, endpoint=endpoint, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - self.child_client = ChildClientOperations(self._client, self._config, self._serialize, self._deserialize) - - def send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/_configuration.py deleted file mode 100644 index fcf8902eb364..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/_configuration.py +++ /dev/null @@ -1,228 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.pipeline import policies - -from .._version import VERSION - - -class HeaderParamClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for HeaderParamClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, name: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if name is None: - raise ValueError("Parameter 'name' must not be None.") - - self.name = name - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - - -class MultipleParamsClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for MultipleParamsClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :param region: The region to use for all operations. This parameter is used as a query - parameter. Required. - :type region: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, name: str, region: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if name is None: - raise ValueError("Parameter 'name' must not be None.") - if region is None: - raise ValueError("Parameter 'region' must not be None.") - - self.name = name - self.region = region - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - - -class MixedParamsClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for MixedParamsClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param name: The name of the client. This parameter is used as a header in all operations. - Required. - :type name: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, name: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if name is None: - raise ValueError("Parameter 'name' must not be None.") - - self.name = name - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - - -class PathParamClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for PathParamClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param blob_name: The name of the blob. This parameter is used as a path parameter in all - operations. Required. - :type blob_name: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, blob_name: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if blob_name is None: - raise ValueError("Parameter 'blob_name' must not be None.") - - self.blob_name = blob_name - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - - -class ParamAliasClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ParamAliasClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param blob_name: Blob name for the client. Required. - :type blob_name: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, blob_name: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if blob_name is None: - raise ValueError("Parameter 'blob_name' must not be None.") - - self.blob_name = blob_name - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - - -class ParentClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for ParentClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param blob_name: The name of the blob. This parameter is used as a path parameter in all - operations. Required. - :type blob_name: str - :param endpoint: Service host. Default value is "http://localhost:3000". - :type endpoint: str - """ - - def __init__(self, blob_name: str, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - if blob_name is None: - raise ValueError("Parameter 'blob_name' must not be None.") - - self.blob_name = blob_name - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-clientinitialization/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/operations/__init__.py deleted file mode 100644 index 55b4923903eb..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/operations/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import _HeaderParamClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import _MultipleParamsClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import _MixedParamsClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import _PathParamClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import _ParamAliasClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import ChildClientOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ChildClientOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/operations/_operations.py deleted file mode 100644 index f9d5c19952c4..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/operations/_operations.py +++ /dev/null @@ -1,960 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -import json -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.model_base import SdkJSONEncoder, _deserialize -from ..._utils.serialization import Deserializer, Serializer -from ..._utils.utils import ClientMixinABC -from ...operations._operations import ( - build_child_client_delete_standalone_request, - build_child_client_get_standalone_request, - build_child_client_with_query_request, - build_header_param_with_body_request, - build_header_param_with_query_request, - build_mixed_params_with_body_request, - build_mixed_params_with_query_request, - build_multiple_params_with_body_request, - build_multiple_params_with_query_request, - build_param_alias_with_aliased_name_request, - build_param_alias_with_original_name_request, - build_path_param_delete_standalone_request, - build_path_param_get_standalone_request, - build_path_param_with_query_request, -) -from .._configuration import ( - HeaderParamClientConfiguration, - MixedParamsClientConfiguration, - MultipleParamsClientConfiguration, - ParamAliasClientConfiguration, - ParentClientConfiguration, - PathParamClientConfiguration, -) - -JSON = MutableMapping[str, Any] -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class _HeaderParamClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], HeaderParamClientConfiguration] -): - - @distributed_trace_async - async def with_query(self, *, id: str, **kwargs: Any) -> None: - """with_query. - - :keyword id: Required. - :paramtype id: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_header_param_with_query_request( - id=id, - name=self._config.name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def with_body(self, body: _models.Input, *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.Input - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def with_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def with_body(self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def with_body(self, body: Union[_models.Input, JSON, IO[bytes]], **kwargs: Any) -> None: - """with_body. - - :param body: Is one of the following types: Input, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.Input or JSON or - IO[bytes] - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_header_param_with_body_request( - name=self._config.name, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class _MultipleParamsClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], MultipleParamsClientConfiguration] -): - - @distributed_trace_async - async def with_query(self, *, id: str, **kwargs: Any) -> None: - """with_query. - - :keyword id: Required. - :paramtype id: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_multiple_params_with_query_request( - id=id, - name=self._config.name, - region=self._config.region, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def with_body(self, body: _models.Input, *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.Input - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def with_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def with_body(self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def with_body(self, body: Union[_models.Input, JSON, IO[bytes]], **kwargs: Any) -> None: - """with_body. - - :param body: Is one of the following types: Input, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.Input or JSON or - IO[bytes] - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_multiple_params_with_body_request( - name=self._config.name, - region=self._config.region, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class _MixedParamsClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], MixedParamsClientConfiguration] -): - - @distributed_trace_async - async def with_query(self, *, region: str, id: str, **kwargs: Any) -> None: - """with_query. - - :keyword region: Required. - :paramtype region: str - :keyword id: Required. - :paramtype id: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_mixed_params_with_query_request( - region=region, - id=id, - name=self._config.name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def with_body( - self, body: _models.WithBodyRequest, *, region: str, content_type: str = "application/json", **kwargs: Any - ) -> None: - """with_body. - - :param body: Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.WithBodyRequest - :keyword region: Required. - :paramtype region: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def with_body( - self, body: JSON, *, region: str, content_type: str = "application/json", **kwargs: Any - ) -> None: - """with_body. - - :param body: Required. - :type body: JSON - :keyword region: Required. - :paramtype region: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def with_body( - self, body: IO[bytes], *, region: str, content_type: str = "application/json", **kwargs: Any - ) -> None: - """with_body. - - :param body: Required. - :type body: IO[bytes] - :keyword region: Required. - :paramtype region: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def with_body( - self, body: Union[_models.WithBodyRequest, JSON, IO[bytes]], *, region: str, **kwargs: Any - ) -> None: - """with_body. - - :param body: Is one of the following types: WithBodyRequest, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.WithBodyRequest or - JSON or IO[bytes] - :keyword region: Required. - :paramtype region: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_mixed_params_with_body_request( - region=region, - name=self._config.name, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class _PathParamClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], PathParamClientConfiguration] -): - - @distributed_trace_async - async def with_query(self, *, format: Optional[str] = None, **kwargs: Any) -> None: - """with_query. - - :keyword format: Default value is None. - :paramtype format: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_path_param_with_query_request( - blob_name=self._config.blob_name, - format=format, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_standalone(self, **kwargs: Any) -> _models.BlobProperties: - """get_standalone. - - :return: BlobProperties. The BlobProperties is compatible with MutableMapping - :rtype: ~specs.azure.clientgenerator.core.clientinitialization.models.BlobProperties - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.BlobProperties] = kwargs.pop("cls", None) - - _request = build_path_param_get_standalone_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.BlobProperties, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_standalone(self, **kwargs: Any) -> None: - """delete_standalone. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_path_param_delete_standalone_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class _ParamAliasClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], ParamAliasClientConfiguration] -): - - @distributed_trace_async - async def with_aliased_name(self, **kwargs: Any) -> None: - """with_aliased_name. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_param_alias_with_aliased_name_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def with_original_name(self, **kwargs: Any) -> None: - """with_original_name. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_param_alias_with_original_name_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class ChildClientOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~specs.azure.clientgenerator.core.clientinitialization.aio.ParentClient`'s - :attr:`child_client` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ParentClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def with_query(self, *, format: Optional[str] = None, **kwargs: Any) -> None: - """with_query. - - :keyword format: Default value is None. - :paramtype format: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_child_client_with_query_request( - blob_name=self._config.blob_name, - format=format, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_standalone(self, **kwargs: Any) -> _models.BlobProperties: - """get_standalone. - - :return: BlobProperties. The BlobProperties is compatible with MutableMapping - :rtype: ~specs.azure.clientgenerator.core.clientinitialization.models.BlobProperties - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.BlobProperties] = kwargs.pop("cls", None) - - _request = build_child_client_get_standalone_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.BlobProperties, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_standalone(self, **kwargs: Any) -> None: - """delete_standalone. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_child_client_delete_standalone_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/aio/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/models/_models.py deleted file mode 100644 index 5a973dd3c659..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/models/_models.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=useless-super-delegation - -import datetime -from typing import Any, Mapping, overload - -from .._utils.model_base import Model as _Model, rest_field - - -class BlobProperties(_Model): - """Properties of a blob. - - :ivar name: Required. - :vartype name: str - :ivar size: Required. - :vartype size: int - :ivar content_type: Required. - :vartype content_type: str - :ivar created_on: Required. - :vartype created_on: ~datetime.datetime - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - size: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - content_type: str = rest_field(name="contentType", visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - created_on: datetime.datetime = rest_field( - name="createdOn", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" - ) - """Required.""" - - @overload - def __init__( - self, - *, - name: str, - size: int, - content_type: str, - created_on: datetime.datetime, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class Input(_Model): - """Input. - - :ivar name: Required. - :vartype name: str - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - name: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class WithBodyRequest(_Model): - """WithBodyRequest. - - :ivar name: Required. - :vartype name: str - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - name: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/models/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/operations/__init__.py deleted file mode 100644 index 55b4923903eb..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/operations/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import _HeaderParamClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import _MultipleParamsClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import _MixedParamsClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import _PathParamClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import _ParamAliasClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import ChildClientOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "ChildClientOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/operations/_operations.py deleted file mode 100644 index 9f103b354575..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/operations/_operations.py +++ /dev/null @@ -1,1190 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -import json -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import ( - HeaderParamClientConfiguration, - MixedParamsClientConfiguration, - MultipleParamsClientConfiguration, - ParamAliasClientConfiguration, - ParentClientConfiguration, - PathParamClientConfiguration, -) -from .._utils.model_base import SdkJSONEncoder, _deserialize -from .._utils.serialization import Deserializer, Serializer -from .._utils.utils import ClientMixinABC - -JSON = MutableMapping[str, Any] -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_header_param_with_query_request(*, id: str, name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/azure/client-generator-core/client-initialization/header-param/with-query" - - # Construct parameters - _params["id"] = _SERIALIZER.query("id", id, "str") - - # Construct headers - _headers["name"] = _SERIALIZER.header("name", name, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_header_param_with_body_request(*, name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - # Construct URL - _url = "/azure/client-generator-core/client-initialization/header-param/with-body" - - # Construct headers - _headers["name"] = _SERIALIZER.header("name", name, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_multiple_params_with_query_request(*, id: str, name: str, region: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/azure/client-generator-core/client-initialization/multiple-params/with-query" - - # Construct parameters - _params["region"] = _SERIALIZER.query("region", region, "str") - _params["id"] = _SERIALIZER.query("id", id, "str") - - # Construct headers - _headers["name"] = _SERIALIZER.header("name", name, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_multiple_params_with_body_request(*, name: str, region: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - # Construct URL - _url = "/azure/client-generator-core/client-initialization/multiple-params/with-body" - - # Construct parameters - _params["region"] = _SERIALIZER.query("region", region, "str") - - # Construct headers - _headers["name"] = _SERIALIZER.header("name", name, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_mixed_params_with_query_request(*, region: str, id: str, name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/azure/client-generator-core/client-initialization/mixed-params/with-query" - - # Construct parameters - _params["region"] = _SERIALIZER.query("region", region, "str") - _params["id"] = _SERIALIZER.query("id", id, "str") - - # Construct headers - _headers["name"] = _SERIALIZER.header("name", name, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_mixed_params_with_body_request(*, region: str, name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - # Construct URL - _url = "/azure/client-generator-core/client-initialization/mixed-params/with-body" - - # Construct parameters - _params["region"] = _SERIALIZER.query("region", region, "str") - - # Construct headers - _headers["name"] = _SERIALIZER.header("name", name, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_path_param_with_query_request(blob_name: str, *, format: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/azure/client-generator-core/client-initialization/path/{blobName}/with-query" - path_format_arguments = { - "blobName": _SERIALIZER.url("blob_name", blob_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if format is not None: - _params["format"] = _SERIALIZER.query("format", format, "str") - - return HttpRequest(method="GET", url=_url, params=_params, **kwargs) - - -def build_path_param_get_standalone_request(blob_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azure/client-generator-core/client-initialization/path/{blobName}/get-standalone" - path_format_arguments = { - "blobName": _SERIALIZER.url("blob_name", blob_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_path_param_delete_standalone_request( # pylint: disable=name-too-long - blob_name: str, **kwargs: Any -) -> HttpRequest: - # Construct URL - _url = "/azure/client-generator-core/client-initialization/path/{blobName}" - path_format_arguments = { - "blobName": _SERIALIZER.url("blob_name", blob_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - return HttpRequest(method="DELETE", url=_url, **kwargs) - - -def build_param_alias_with_aliased_name_request( # pylint: disable=name-too-long - blob_name: str, **kwargs: Any -) -> HttpRequest: - # Construct URL - _url = "/azure/client-generator-core/client-initialization/param-alias/{blob}/with-aliased-name" - path_format_arguments = { - "blob": _SERIALIZER.url("blob_name", blob_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_param_alias_with_original_name_request( # pylint: disable=name-too-long - blob_name: str, **kwargs: Any -) -> HttpRequest: - # Construct URL - _url = "/azure/client-generator-core/client-initialization/param-alias/{blobName}/with-original-name" - path_format_arguments = { - "blobName": _SERIALIZER.url("blob_name", blob_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_child_client_with_query_request( - blob_name: str, *, format: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/azure/client-generator-core/client-initialization/child-client/{blobName}/with-query" - path_format_arguments = { - "blobName": _SERIALIZER.url("blob_name", blob_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if format is not None: - _params["format"] = _SERIALIZER.query("format", format, "str") - - return HttpRequest(method="GET", url=_url, params=_params, **kwargs) - - -def build_child_client_get_standalone_request( # pylint: disable=name-too-long - blob_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azure/client-generator-core/client-initialization/child-client/{blobName}/get-standalone" - path_format_arguments = { - "blobName": _SERIALIZER.url("blob_name", blob_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_child_client_delete_standalone_request( # pylint: disable=name-too-long - blob_name: str, **kwargs: Any -) -> HttpRequest: - # Construct URL - _url = "/azure/client-generator-core/client-initialization/child-client/{blobName}" - path_format_arguments = { - "blobName": _SERIALIZER.url("blob_name", blob_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - return HttpRequest(method="DELETE", url=_url, **kwargs) - - -class _HeaderParamClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], HeaderParamClientConfiguration] -): - - @distributed_trace - def with_query(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """with_query. - - :keyword id: Required. - :paramtype id: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_header_param_with_query_request( - id=id, - name=self._config.name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def with_body(self, body: _models.Input, *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.Input - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def with_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def with_body(self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def with_body( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.Input, JSON, IO[bytes]], **kwargs: Any - ) -> None: - """with_body. - - :param body: Is one of the following types: Input, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.Input or JSON or - IO[bytes] - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_header_param_with_body_request( - name=self._config.name, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class _MultipleParamsClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], MultipleParamsClientConfiguration] -): - - @distributed_trace - def with_query(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """with_query. - - :keyword id: Required. - :paramtype id: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_multiple_params_with_query_request( - id=id, - name=self._config.name, - region=self._config.region, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def with_body(self, body: _models.Input, *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.Input - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def with_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def with_body(self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def with_body( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.Input, JSON, IO[bytes]], **kwargs: Any - ) -> None: - """with_body. - - :param body: Is one of the following types: Input, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.Input or JSON or - IO[bytes] - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_multiple_params_with_body_request( - name=self._config.name, - region=self._config.region, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class _MixedParamsClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], MixedParamsClientConfiguration] -): - - @distributed_trace - def with_query( # pylint: disable=inconsistent-return-statements - self, *, region: str, id: str, **kwargs: Any - ) -> None: - """with_query. - - :keyword region: Required. - :paramtype region: str - :keyword id: Required. - :paramtype id: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_mixed_params_with_query_request( - region=region, - id=id, - name=self._config.name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def with_body( - self, body: _models.WithBodyRequest, *, region: str, content_type: str = "application/json", **kwargs: Any - ) -> None: - """with_body. - - :param body: Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.WithBodyRequest - :keyword region: Required. - :paramtype region: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def with_body(self, body: JSON, *, region: str, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: JSON - :keyword region: Required. - :paramtype region: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def with_body(self, body: IO[bytes], *, region: str, content_type: str = "application/json", **kwargs: Any) -> None: - """with_body. - - :param body: Required. - :type body: IO[bytes] - :keyword region: Required. - :paramtype region: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def with_body( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.WithBodyRequest, JSON, IO[bytes]], *, region: str, **kwargs: Any - ) -> None: - """with_body. - - :param body: Is one of the following types: WithBodyRequest, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.clientinitialization.models.WithBodyRequest or - JSON or IO[bytes] - :keyword region: Required. - :paramtype region: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_mixed_params_with_body_request( - region=region, - name=self._config.name, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class _PathParamClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], PathParamClientConfiguration] -): - - @distributed_trace - def with_query( # pylint: disable=inconsistent-return-statements - self, *, format: Optional[str] = None, **kwargs: Any - ) -> None: - """with_query. - - :keyword format: Default value is None. - :paramtype format: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_path_param_with_query_request( - blob_name=self._config.blob_name, - format=format, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_standalone(self, **kwargs: Any) -> _models.BlobProperties: - """get_standalone. - - :return: BlobProperties. The BlobProperties is compatible with MutableMapping - :rtype: ~specs.azure.clientgenerator.core.clientinitialization.models.BlobProperties - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.BlobProperties] = kwargs.pop("cls", None) - - _request = build_path_param_get_standalone_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.BlobProperties, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_standalone(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """delete_standalone. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_path_param_delete_standalone_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class _ParamAliasClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], ParamAliasClientConfiguration] -): - - @distributed_trace - def with_aliased_name(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """with_aliased_name. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_param_alias_with_aliased_name_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def with_original_name(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """with_original_name. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_param_alias_with_original_name_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class ChildClientOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~specs.azure.clientgenerator.core.clientinitialization.ParentClient`'s - :attr:`child_client` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: ParentClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def with_query( # pylint: disable=inconsistent-return-statements - self, *, format: Optional[str] = None, **kwargs: Any - ) -> None: - """with_query. - - :keyword format: Default value is None. - :paramtype format: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_child_client_with_query_request( - blob_name=self._config.blob_name, - format=format, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_standalone(self, **kwargs: Any) -> _models.BlobProperties: - """get_standalone. - - :return: BlobProperties. The BlobProperties is compatible with MutableMapping - :rtype: ~specs.azure.clientgenerator.core.clientinitialization.models.BlobProperties - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.BlobProperties] = kwargs.pop("cls", None) - - _request = build_child_client_get_standalone_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.BlobProperties, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_standalone(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """delete_standalone. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_child_client_delete_standalone_request( - blob_name=self._config.blob_name, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/operations/_patch.py deleted file mode 100644 index 8bcb627aa475..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/operations/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/pyproject.toml index 3eaa21601fd7..cfd257f485a7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/types.py deleted file mode 100644 index a2ad927fac5d..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-method-parameter-to-client/specs/azure/clientgenerator/core/clientlocation/parameter/types.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing_extensions import Required, TypedDict - - -class Blob(TypedDict, total=False): - """Blob. - - :ivar id: Required. - :vartype id: str - :ivar name: Required. - :vartype name: str - :ivar size: Required. - :vartype size: int - :ivar path: Required. - :vartype path: str - """ - - id: Required[str] - """Required.""" - name: Required[str] - """Required.""" - size: Required[int] - """Required.""" - path: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/pyproject.toml index e316f068200f..8b00f3780614 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-existing-sub-client/specs/azure/clientgenerator/core/clientlocation/subclient/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/pyproject.toml index a798b23e0025..f6761989221e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-new-sub-client/specs/azure/clientgenerator/core/clientlocation/newsubclient/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/pyproject.toml index 7cd0046e517d..e3ff876fb883 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-location-move-to-root-client/specs/azure/clientgenerator/core/clientlocation/rootclient/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/pyproject.toml index da28d960f271..75377e8c1079 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/apiview-properties.json index 326bdd8a7bfa..eb65a06ddf06 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/apiview-properties.json +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/apiview-properties.json @@ -1,12 +1,20 @@ { "CrossLanguagePackageId": "_Specs_.Azure.ClientGenerator.Core.ExactName", "CrossLanguageDefinitionId": { + "specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig": "_Specs_.Azure.ClientGenerator.Core.ExactName.EnumValue.EndpointConfig", "specs.azure.clientgenerator.core.exactname.model.models.My_model": "_Specs_.Azure.ClientGenerator.Core.ExactName.Model.ExactModel", "specs.azure.clientgenerator.core.exactname.property.models.ScopedModel": "_Specs_.Azure.ClientGenerator.Core.ExactName.Property.ScopedModel", + "specs.azure.clientgenerator.core.exactname.models.AgentEndpointProtocol": "_Specs_.Azure.ClientGenerator.Core.ExactName.EnumValue.AgentEndpointProtocol", "specs.azure.clientgenerator.core.exactname.operations.ModelOperations.send": "_Specs_.Azure.ClientGenerator.Core.ExactName.Model.send", "specs.azure.clientgenerator.core.exactname.aio.operations.ModelOperations.send": "_Specs_.Azure.ClientGenerator.Core.ExactName.Model.send", "specs.azure.clientgenerator.core.exactname.operations.PropertyOperations.send": "_Specs_.Azure.ClientGenerator.Core.ExactName.Property.send", - "specs.azure.clientgenerator.core.exactname.aio.operations.PropertyOperations.send": "_Specs_.Azure.ClientGenerator.Core.ExactName.Property.send" + "specs.azure.clientgenerator.core.exactname.aio.operations.PropertyOperations.send": "_Specs_.Azure.ClientGenerator.Core.ExactName.Property.send", + "specs.azure.clientgenerator.core.exactname.operations.EnumValueOperations.send": "_Specs_.Azure.ClientGenerator.Core.ExactName.EnumValue.send", + "specs.azure.clientgenerator.core.exactname.aio.operations.EnumValueOperations.send": "_Specs_.Azure.ClientGenerator.Core.ExactName.EnumValue.send", + "specs.azure.clientgenerator.core.exactname.operations.OperationOperations.myOp": "_Specs_.Azure.ClientGenerator.Core.ExactName.Operation.myOp", + "specs.azure.clientgenerator.core.exactname.aio.operations.OperationOperations.myOp": "_Specs_.Azure.ClientGenerator.Core.ExactName.Operation.myOp", + "specs.azure.clientgenerator.core.exactname.operations.ParameterOperations.send": "_Specs_.Azure.ClientGenerator.Core.ExactName.Parameter.send", + "specs.azure.clientgenerator.core.exactname.aio.operations.ParameterOperations.send": "_Specs_.Azure.ClientGenerator.Core.ExactName.Parameter.send" }, - "CrossLanguageVersion": "cc4f69ca2424" + "CrossLanguageVersion": "29dab5aacd02" } \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_param_alias.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_enum_value_operations.py similarity index 54% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_param_alias.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_enum_value_operations.py index 8680bbb0cd5e..474107c950e7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_param_alias.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_enum_value_operations.py @@ -7,25 +7,18 @@ # -------------------------------------------------------------------------- import pytest from devtools_testutils import recorded_by_proxy -from testpreparer import ParamAliasClientTestBase, ParamAliasPreparer +from testpreparer import ExactNameClientTestBase, ExactNamePreparer @pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestParamAlias(ParamAliasClientTestBase): - @ParamAliasPreparer() +class TestExactNameEnumValueOperations(ExactNameClientTestBase): + @ExactNamePreparer() @recorded_by_proxy - def test_with_aliased_name(self, paramalias_endpoint): - client = self.create_client(endpoint=paramalias_endpoint) - response = client.with_aliased_name() - - # please add some check logic here by yourself - # ... - - @ParamAliasPreparer() - @recorded_by_proxy - def test_with_original_name(self, paramalias_endpoint): - client = self.create_client(endpoint=paramalias_endpoint) - response = client.with_original_name() + def test_enum_value_send(self, exactname_endpoint): + client = self.create_client(endpoint=exactname_endpoint) + response = client.enum_value.send( + body={"protocol": "str"}, + ) # please add some check logic here by yourself # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_param_alias_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_enum_value_operations_async.py similarity index 51% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_param_alias_async.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_enum_value_operations_async.py index a9afaa016869..5c7defe80076 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_param_alias_async.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_enum_value_operations_async.py @@ -7,26 +7,19 @@ # -------------------------------------------------------------------------- import pytest from devtools_testutils.aio import recorded_by_proxy_async -from testpreparer import ParamAliasPreparer -from testpreparer_async import ParamAliasClientTestBaseAsync +from testpreparer import ExactNamePreparer +from testpreparer_async import ExactNameClientTestBaseAsync @pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestParamAliasAsync(ParamAliasClientTestBaseAsync): - @ParamAliasPreparer() +class TestExactNameEnumValueOperationsAsync(ExactNameClientTestBaseAsync): + @ExactNamePreparer() @recorded_by_proxy_async - async def test_with_aliased_name(self, paramalias_endpoint): - client = self.create_async_client(endpoint=paramalias_endpoint) - response = await client.with_aliased_name() - - # please add some check logic here by yourself - # ... - - @ParamAliasPreparer() - @recorded_by_proxy_async - async def test_with_original_name(self, paramalias_endpoint): - client = self.create_async_client(endpoint=paramalias_endpoint) - response = await client.with_original_name() + async def test_enum_value_send(self, exactname_endpoint): + client = self.create_async_client(endpoint=exactname_endpoint) + response = await client.enum_value.send( + body={"protocol": "str"}, + ) # please add some check logic here by yourself # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_operation_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_operation_operations.py new file mode 100644 index 000000000000..f5e3b38307a5 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_operation_operations.py @@ -0,0 +1,22 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import ExactNameClientTestBase, ExactNamePreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestExactNameOperationOperations(ExactNameClientTestBase): + @ExactNamePreparer() + @recorded_by_proxy + def test_operation_myOp(self, exactname_endpoint): + client = self.create_client(endpoint=exactname_endpoint) + response = client.operation.myOp() + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_operation_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_operation_operations_async.py new file mode 100644 index 000000000000..f25007b29410 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_operation_operations_async.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import ExactNamePreparer +from testpreparer_async import ExactNameClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestExactNameOperationOperationsAsync(ExactNameClientTestBaseAsync): + @ExactNamePreparer() + @recorded_by_proxy_async + async def test_operation_myOp(self, exactname_endpoint): + client = self.create_async_client(endpoint=exactname_endpoint) + response = await client.operation.myOp() + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_mixed_params.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_parameter_operations.py similarity index 50% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_mixed_params.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_parameter_operations.py index 396cff2001fb..391b2f9bd2ed 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_mixed_params.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_parameter_operations.py @@ -7,30 +7,17 @@ # -------------------------------------------------------------------------- import pytest from devtools_testutils import recorded_by_proxy -from testpreparer import MixedParamsClientTestBase, MixedParamsPreparer +from testpreparer import ExactNameClientTestBase, ExactNamePreparer @pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestMixedParams(MixedParamsClientTestBase): - @MixedParamsPreparer() +class TestExactNameParameterOperations(ExactNameClientTestBase): + @ExactNamePreparer() @recorded_by_proxy - def test_with_query(self, mixedparams_endpoint): - client = self.create_client(endpoint=mixedparams_endpoint) - response = client.with_query( - region="str", - id="str", - ) - - # please add some check logic here by yourself - # ... - - @MixedParamsPreparer() - @recorded_by_proxy - def test_with_body(self, mixedparams_endpoint): - client = self.create_client(endpoint=mixedparams_endpoint) - response = client.with_body( - body={"name": "str"}, - region="str", + def test_parameter_send(self, exactname_endpoint): + client = self.create_client(endpoint=exactname_endpoint) + response = client.parameter.send( + myParam="str", ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_parameter_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_parameter_operations_async.py new file mode 100644 index 000000000000..cb191bba9791 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/generated_tests/test_exact_name_parameter_operations_async.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import ExactNamePreparer +from testpreparer_async import ExactNameClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestExactNameParameterOperationsAsync(ExactNameClientTestBaseAsync): + @ExactNamePreparer() + @recorded_by_proxy_async + async def test_parameter_send(self, exactname_endpoint): + client = self.create_async_client(endpoint=exactname_endpoint) + response = await client.parameter.send( + myParam="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/pyproject.toml index 96c3ad87afd5..f9b525347697 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_client.py index 35b7bba12e6c..4c72280dec32 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_client.py @@ -16,7 +16,10 @@ from ._configuration import ExactNameClientConfiguration from ._utils.serialization import Deserializer, Serializer +from .enumvalue.operations import EnumValueOperations from .model.operations import ModelOperations +from .operation.operations import OperationOperations +from .parameter.operations import ParameterOperations from .property.operations import PropertyOperations if sys.version_info >= (3, 11): @@ -32,6 +35,12 @@ class ExactNameClient: # pylint: disable=client-accepts-api-version-keyword :vartype model: specs.azure.clientgenerator.core.exactname.operations.ModelOperations :ivar property: PropertyOperations operations :vartype property: specs.azure.clientgenerator.core.exactname.operations.PropertyOperations + :ivar enum_value: EnumValueOperations operations + :vartype enum_value: specs.azure.clientgenerator.core.exactname.operations.EnumValueOperations + :ivar operation: OperationOperations operations + :vartype operation: specs.azure.clientgenerator.core.exactname.operations.OperationOperations + :ivar parameter: ParameterOperations operations + :vartype parameter: specs.azure.clientgenerator.core.exactname.operations.ParameterOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -66,6 +75,9 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._serialize.client_side_validation = False self.model = ModelOperations(self._client, self._config, self._serialize, self._deserialize) self.property = PropertyOperations(self._client, self._config, self._serialize, self._deserialize) + self.enum_value = EnumValueOperations(self._client, self._config, self._serialize, self._deserialize) + self.operation = OperationOperations(self._client, self._config, self._serialize, self._deserialize) + self.parameter = ParameterOperations(self._client, self._config, self._serialize, self._deserialize) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/aio/_client.py index c3f605866702..5562671580d5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/aio/_client.py @@ -15,7 +15,10 @@ from azure.core.rest import AsyncHttpResponse, HttpRequest from .._utils.serialization import Deserializer, Serializer +from ..enumvalue.aio.operations import EnumValueOperations from ..model.aio.operations import ModelOperations +from ..operation.aio.operations import OperationOperations +from ..parameter.aio.operations import ParameterOperations from ..property.aio.operations import PropertyOperations from ._configuration import ExactNameClientConfiguration @@ -32,6 +35,15 @@ class ExactNameClient: # pylint: disable=client-accepts-api-version-keyword :vartype model: specs.azure.clientgenerator.core.exactname.aio.operations.ModelOperations :ivar property: PropertyOperations operations :vartype property: specs.azure.clientgenerator.core.exactname.aio.operations.PropertyOperations + :ivar enum_value: EnumValueOperations operations + :vartype enum_value: + specs.azure.clientgenerator.core.exactname.aio.operations.EnumValueOperations + :ivar operation: OperationOperations operations + :vartype operation: + specs.azure.clientgenerator.core.exactname.aio.operations.OperationOperations + :ivar parameter: ParameterOperations operations + :vartype parameter: + specs.azure.clientgenerator.core.exactname.aio.operations.ParameterOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -66,6 +78,9 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._serialize.client_side_validation = False self.model = ModelOperations(self._client, self._config, self._serialize, self._deserialize) self.property = PropertyOperations(self._client, self._config, self._serialize, self._deserialize) + self.enum_value = EnumValueOperations(self._client, self._config, self._serialize, self._deserialize) + self.operation = OperationOperations(self._client, self._config, self._serialize, self._deserialize) + self.parameter = ParameterOperations(self._client, self._config, self._serialize, self._deserialize) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/__init__.py similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/__init__.py similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/operations/__init__.py similarity index 86% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_operations/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/operations/__init__.py index 46bd9b49069a..1bbd9d9cfbc8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/operations/__init__.py @@ -12,12 +12,14 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import _TwoOperationGroupClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import EnumValueOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [] +__all__ = [ + "EnumValueOperations", +] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/operations/_operations.py new file mode 100644 index 000000000000..adca2c1dd7f1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/operations/_operations.py @@ -0,0 +1,174 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models2, types as _types_models2 +from ...._utils.model_base import SdkJSONEncoder, _deserialize +from ...._utils.serialization import Deserializer, Serializer +from ....aio._configuration import ExactNameClientConfiguration +from ...operations._operations import build_enum_value_send_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class EnumValueOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~specs.azure.clientgenerator.core.exactname.aio.ExactNameClient`'s + :attr:`enum_value` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ExactNameClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def send( + self, body: _models2.EndpointConfig, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.EndpointConfig: + """send. + + :param body: Required. + :type body: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EndpointConfig. The EndpointConfig is compatible with MutableMapping + :rtype: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def send( + self, body: _types_models2.EndpointConfig, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.EndpointConfig: + """send. + + :param body: Required. + :type body: ~specs.azure.clientgenerator.core.exactname.enumvalue.types.EndpointConfig + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EndpointConfig. The EndpointConfig is compatible with MutableMapping + :rtype: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def send( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.EndpointConfig: + """send. + + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: EndpointConfig. The EndpointConfig is compatible with MutableMapping + :rtype: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def send( + self, body: Union[_models2.EndpointConfig, _types_models2.EndpointConfig, IO[bytes]], **kwargs: Any + ) -> _models2.EndpointConfig: + """send. + + :param body: Is either a EndpointConfig type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig or + ~specs.azure.clientgenerator.core.exactname.enumvalue.types.EndpointConfig or IO[bytes] + :return: EndpointConfig. The EndpointConfig is compatible with MutableMapping + :rtype: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.EndpointConfig] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_enum_value_send_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models2.EndpointConfig, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/operations/_patch.py similarity index 99% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_operations/_patch.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/__init__.py new file mode 100644 index 000000000000..675050397f8f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + EndpointConfig, +) + +from ._enums import ( # type: ignore + AgentEndpointProtocol, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "EndpointConfig", + "AgentEndpointProtocol", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/_enums.py similarity index 57% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/types.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/_enums.py index 2f43503b4b5a..a82305e35f9d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/_enums.py @@ -6,15 +6,18 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing_extensions import Required, TypedDict +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta -class Test(TypedDict, total=False): - """Test model. +class AgentEndpointProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of AgentEndpointProtocol.""" - :ivar id: The id of the test. Required. - :vartype id: str - """ - - id: Required[str] - """The id of the test. Required.""" + ACTIVITY = "activity" + """ACTIVITY.""" + RESPONSES = "responses" + """RESPONSES.""" + A2A = "a2a" + """A2A.""" + MCP = "mcp" + """MCP.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/_models.py new file mode 100644 index 000000000000..0666b51f0365 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/_models.py @@ -0,0 +1,46 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +from typing import Any, Mapping, TYPE_CHECKING, Union, overload + +from ..._utils.model_base import Model as _Model, rest_field + +if TYPE_CHECKING: + from .. import models as _models + + +class EndpointConfig(_Model): + """EndpointConfig. + + :ivar protocol: Required. Known values are: "activity", "responses", "a2a", and "mcp". + :vartype protocol: str or + ~specs.azure.clientgenerator.core.exactname.enumvalue.models.AgentEndpointProtocol + """ + + protocol: Union[str, "_models.AgentEndpointProtocol"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Required. Known values are: \"activity\", \"responses\", \"a2a\", and \"mcp\".""" + + @overload + def __init__( + self, + *, + protocol: Union[str, "_models.AgentEndpointProtocol"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/_patch.py similarity index 99% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_operations/_patch.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/operations/__init__.py similarity index 86% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_operations/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/operations/__init__.py index 46bd9b49069a..1bbd9d9cfbc8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/operations/__init__.py @@ -12,12 +12,14 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import _TwoOperationGroupClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import EnumValueOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [] +__all__ = [ + "EnumValueOperations", +] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/operations/_operations.py new file mode 100644 index 000000000000..b874362c9e55 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/operations/_operations.py @@ -0,0 +1,193 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models1, types as _types_models1 +from ..._configuration import ExactNameClientConfiguration +from ..._utils.model_base import SdkJSONEncoder, _deserialize +from ..._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_enum_value_send_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/azure/client-generator-core/exact-name/enum-value" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +class EnumValueOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~specs.azure.clientgenerator.core.exactname.ExactNameClient`'s + :attr:`enum_value` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ExactNameClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def send( + self, body: _models1.EndpointConfig, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.EndpointConfig: + """send. + + :param body: Required. + :type body: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EndpointConfig. The EndpointConfig is compatible with MutableMapping + :rtype: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def send( + self, body: _types_models1.EndpointConfig, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.EndpointConfig: + """send. + + :param body: Required. + :type body: ~specs.azure.clientgenerator.core.exactname.enumvalue.types.EndpointConfig + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EndpointConfig. The EndpointConfig is compatible with MutableMapping + :rtype: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def send( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.EndpointConfig: + """send. + + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: EndpointConfig. The EndpointConfig is compatible with MutableMapping + :rtype: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def send( + self, body: Union[_models1.EndpointConfig, _types_models1.EndpointConfig, IO[bytes]], **kwargs: Any + ) -> _models1.EndpointConfig: + """send. + + :param body: Is either a EndpointConfig type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig or + ~specs.azure.clientgenerator.core.exactname.enumvalue.types.EndpointConfig or IO[bytes] + :return: EndpointConfig. The EndpointConfig is compatible with MutableMapping + :rtype: ~specs.azure.clientgenerator.core.exactname.enumvalue.models.EndpointConfig + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.EndpointConfig] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_enum_value_send_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models1.EndpointConfig, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/operations/_patch.py similarity index 99% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_operations/_patch.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/types.py similarity index 58% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/types.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/types.py index ecad43683d2a..2d17e526e801 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/enumvalue/types.py @@ -10,15 +10,15 @@ from typing_extensions import Required, TypedDict if TYPE_CHECKING: - from .submodels import SecondClientEnumType + from .models import AgentEndpointProtocol -class SecondClientResult(TypedDict, total=False): - """SecondClientResult. +class EndpointConfig(TypedDict, total=False): + """EndpointConfig. - :ivar type: Required. "second" - :vartype type: str or ~client.clientnamespace.second.sub.models.SecondClientEnumType + :ivar protocol: Required. Known values are: "activity", "responses", "a2a", and "mcp". + :vartype protocol: Union[str, "AgentEndpointProtocol"] """ - type: Required[Union[str, "SecondClientEnumType"]] - """Required. \"second\"""" + protocol: Required[Union[str, "AgentEndpointProtocol"]] + """Required. Known values are: \"activity\", \"responses\", \"a2a\", and \"mcp\".""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/model/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/model/aio/operations/_operations.py index 5b3b3ad0405e..fb832d9582b4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/model/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/model/aio/operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import ExactNameClientConfiguration from ...operations._operations import build_model_send_request -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -71,11 +70,13 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models2.My_model: + async def send( + self, body: _types_models2.My_model, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.My_model: """send. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.exactname.model.types.My_model :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -101,12 +102,14 @@ async def send( """ @distributed_trace_async - async def send(self, body: Union[_models2.My_model, JSON, IO[bytes]], **kwargs: Any) -> _models2.My_model: + async def send( + self, body: Union[_models2.My_model, _types_models2.My_model, IO[bytes]], **kwargs: Any + ) -> _models2.My_model: """send. - :param body: Is one of the following types: My_model, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.exactname.model.models.My_model or JSON or - IO[bytes] + :param body: Is either a My_model type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.exactname.model.models.My_model or + ~specs.azure.clientgenerator.core.exactname.model.types.My_model or IO[bytes] :return: My_model. The My_model is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.exactname.model.models.My_model :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/model/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/model/operations/_operations.py index 20e46e6b1b87..057dd94e31b9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/model/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/model/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from ..._configuration import ExactNameClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -90,11 +89,13 @@ def send( """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models1.My_model: + def send( + self, body: _types_models1.My_model, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.My_model: """send. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.exactname.model.types.My_model :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -118,12 +119,14 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ @distributed_trace - def send(self, body: Union[_models1.My_model, JSON, IO[bytes]], **kwargs: Any) -> _models1.My_model: + def send( + self, body: Union[_models1.My_model, _types_models1.My_model, IO[bytes]], **kwargs: Any + ) -> _models1.My_model: """send. - :param body: Is one of the following types: My_model, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.exactname.model.models.My_model or JSON or - IO[bytes] + :param body: Is either a My_model type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.exactname.model.models.My_model or + ~specs.azure.clientgenerator.core.exactname.model.types.My_model or IO[bytes] :return: My_model. The My_model is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.exactname.model.models.My_model :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/__init__.py similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/__init__.py similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/operations/__init__.py new file mode 100644 index 000000000000..946aa7df9d4f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import OperationOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "OperationOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/operations/_operations.py new file mode 100644 index 000000000000..404c7e15109d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/operations/_operations.py @@ -0,0 +1,91 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async + +from ...._utils.serialization import Deserializer, Serializer +from ....aio._configuration import ExactNameClientConfiguration +from ...operations._operations import build_operation_myOp_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class OperationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~specs.azure.clientgenerator.core.exactname.aio.ExactNameClient`'s + :attr:`operation` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ExactNameClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def myOp(self, **kwargs: Any) -> None: + """myOp. + + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_operation_myOp_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/operations/_patch.py similarity index 99% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_operations/_patch.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/operations/__init__.py new file mode 100644 index 000000000000..946aa7df9d4f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import OperationOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "OperationOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/operations/_operations.py new file mode 100644 index 000000000000..d5eaa8adaaf0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/operations/_operations.py @@ -0,0 +1,100 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace + +from ..._configuration import ExactNameClientConfiguration +from ..._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_operation_myOp_request(**kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/azure/client-generator-core/exact-name/operation" + + return HttpRequest(method="GET", url=_url, **kwargs) + + +class OperationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~specs.azure.clientgenerator.core.exactname.ExactNameClient`'s + :attr:`operation` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ExactNameClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def myOp(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """myOp. + + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_operation_myOp_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/operation/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/operations/__init__.py new file mode 100644 index 000000000000..95b293895049 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ParameterOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ParameterOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/operations/_operations.py new file mode 100644 index 000000000000..85558f08c6bb --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/operations/_operations.py @@ -0,0 +1,94 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async + +from ...._utils.serialization import Deserializer, Serializer +from ....aio._configuration import ExactNameClientConfiguration +from ...operations._operations import build_parameter_send_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class ParameterOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~specs.azure.clientgenerator.core.exactname.aio.ExactNameClient`'s + :attr:`parameter` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ExactNameClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def send(self, *, myParam: str, **kwargs: Any) -> None: + """send. + + :keyword myParam: Required. + :paramtype myParam: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_parameter_send_request( + myParam=myParam, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/operations/__init__.py new file mode 100644 index 000000000000..95b293895049 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ParameterOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ParameterOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/operations/_operations.py new file mode 100644 index 000000000000..ca5ca604b7ec --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/operations/_operations.py @@ -0,0 +1,109 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from ..._configuration import ExactNameClientConfiguration +from ..._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_parameter_send_request(*, myParam: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/azure/client-generator-core/exact-name/parameter" + + # Construct parameters + _params["myParam"] = _SERIALIZER.query("myParam", myParam, "str") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + +class ParameterOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~specs.azure.clientgenerator.core.exactname.ExactNameClient`'s + :attr:`parameter` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ExactNameClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def send(self, *, myParam: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """send. + + :keyword myParam: Required. + :paramtype myParam: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_parameter_send_request( + myParam=myParam, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/parameter/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/property/aio/operations/_operations.py index 366c1d1660c2..c188a3809d32 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/property/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/property/aio/operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import ExactNameClientConfiguration from ...operations._operations import build_property_send_request -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -71,11 +70,13 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models2.ScopedModel: + async def send( + self, body: _types_models2.ScopedModel, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.ScopedModel: """send. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.exactname.property.types.ScopedModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -101,12 +102,14 @@ async def send( """ @distributed_trace_async - async def send(self, body: Union[_models2.ScopedModel, JSON, IO[bytes]], **kwargs: Any) -> _models2.ScopedModel: + async def send( + self, body: Union[_models2.ScopedModel, _types_models2.ScopedModel, IO[bytes]], **kwargs: Any + ) -> _models2.ScopedModel: """send. - :param body: Is one of the following types: ScopedModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.exactname.property.models.ScopedModel or JSON or - IO[bytes] + :param body: Is either a ScopedModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.exactname.property.models.ScopedModel or + ~specs.azure.clientgenerator.core.exactname.property.types.ScopedModel or IO[bytes] :return: ScopedModel. The ScopedModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.exactname.property.models.ScopedModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/property/operations/_operations.py index 60830aaa41a2..7455ebae584c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/property/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-exact-name/specs/azure/clientgenerator/core/exactname/property/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from ..._configuration import ExactNameClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -90,11 +89,13 @@ def send( """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models1.ScopedModel: + def send( + self, body: _types_models1.ScopedModel, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.ScopedModel: """send. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.exactname.property.types.ScopedModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -118,12 +119,14 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ @distributed_trace - def send(self, body: Union[_models1.ScopedModel, JSON, IO[bytes]], **kwargs: Any) -> _models1.ScopedModel: + def send( + self, body: Union[_models1.ScopedModel, _types_models1.ScopedModel, IO[bytes]], **kwargs: Any + ) -> _models1.ScopedModel: """send. - :param body: Is one of the following types: ScopedModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.exactname.property.models.ScopedModel or JSON or - IO[bytes] + :param body: Is either a ScopedModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.exactname.property.models.ScopedModel or + ~specs.azure.clientgenerator.core.exactname.property.types.ScopedModel or IO[bytes] :return: ScopedModel. The ScopedModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.exactname.property.models.ScopedModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/pyproject.toml index 21ed005cead7..1a1e740ae3d8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_operations/_operations.py index 5452ea688d6c..082b71d38881 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import FlattenPropertyClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -136,12 +135,12 @@ def put_flatten_model( @overload def put_flatten_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.FlattenModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.FlattenModel: """put_flatten_model. :param input: Required. - :type input: JSON + :type input: ~specs.azure.clientgenerator.core.flattenproperty.types.FlattenModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -168,13 +167,13 @@ def put_flatten_model( @distributed_trace def put_flatten_model( - self, input: Union[_models.FlattenModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.FlattenModel, _types.FlattenModel, IO[bytes]], **kwargs: Any ) -> _models.FlattenModel: """put_flatten_model. - :param input: Is one of the following types: FlattenModel, JSON, IO[bytes] Required. - :type input: ~specs.azure.clientgenerator.core.flattenproperty.models.FlattenModel or JSON or - IO[bytes] + :param input: Is either a FlattenModel type or a IO[bytes] type. Required. + :type input: ~specs.azure.clientgenerator.core.flattenproperty.models.FlattenModel or + ~specs.azure.clientgenerator.core.flattenproperty.types.FlattenModel or IO[bytes] :return: FlattenModel. The FlattenModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.flattenproperty.models.FlattenModel :raises ~azure.core.exceptions.HttpResponseError: @@ -256,12 +255,12 @@ def put_nested_flatten_model( @overload def put_nested_flatten_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.NestedFlattenModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.NestedFlattenModel: """put_nested_flatten_model. :param input: Required. - :type input: JSON + :type input: ~specs.azure.clientgenerator.core.flattenproperty.types.NestedFlattenModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -288,13 +287,13 @@ def put_nested_flatten_model( @distributed_trace def put_nested_flatten_model( - self, input: Union[_models.NestedFlattenModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.NestedFlattenModel, _types.NestedFlattenModel, IO[bytes]], **kwargs: Any ) -> _models.NestedFlattenModel: """put_nested_flatten_model. - :param input: Is one of the following types: NestedFlattenModel, JSON, IO[bytes] Required. + :param input: Is either a NestedFlattenModel type or a IO[bytes] type. Required. :type input: ~specs.azure.clientgenerator.core.flattenproperty.models.NestedFlattenModel or - JSON or IO[bytes] + ~specs.azure.clientgenerator.core.flattenproperty.types.NestedFlattenModel or IO[bytes] :return: NestedFlattenModel. The NestedFlattenModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.flattenproperty.models.NestedFlattenModel :raises ~azure.core.exceptions.HttpResponseError: @@ -376,12 +375,12 @@ def put_flatten_unknown_model( @overload def put_flatten_unknown_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.FlattenUnknownModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.FlattenUnknownModel: """put_flatten_unknown_model. :param input: Required. - :type input: JSON + :type input: ~specs.azure.clientgenerator.core.flattenproperty.types.FlattenUnknownModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -408,13 +407,13 @@ def put_flatten_unknown_model( @distributed_trace def put_flatten_unknown_model( - self, input: Union[_models.FlattenUnknownModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.FlattenUnknownModel, _types.FlattenUnknownModel, IO[bytes]], **kwargs: Any ) -> _models.FlattenUnknownModel: """put_flatten_unknown_model. - :param input: Is one of the following types: FlattenUnknownModel, JSON, IO[bytes] Required. + :param input: Is either a FlattenUnknownModel type or a IO[bytes] type. Required. :type input: ~specs.azure.clientgenerator.core.flattenproperty.models.FlattenUnknownModel or - JSON or IO[bytes] + ~specs.azure.clientgenerator.core.flattenproperty.types.FlattenUnknownModel or IO[bytes] :return: FlattenUnknownModel. The FlattenUnknownModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.flattenproperty.models.FlattenUnknownModel :raises ~azure.core.exceptions.HttpResponseError: @@ -496,12 +495,12 @@ def put_flatten_read_only_model( @overload def put_flatten_read_only_model( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Solution, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Solution: """put_flatten_read_only_model. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.flattenproperty.types.Solution :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -528,13 +527,13 @@ def put_flatten_read_only_model( @distributed_trace def put_flatten_read_only_model( - self, body: Union[_models.Solution, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.Solution, _types.Solution, IO[bytes]], **kwargs: Any ) -> _models.Solution: """put_flatten_read_only_model. - :param body: Is one of the following types: Solution, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.flattenproperty.models.Solution or JSON or - IO[bytes] + :param body: Is either a Solution type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.flattenproperty.models.Solution or + ~specs.azure.clientgenerator.core.flattenproperty.types.Solution or IO[bytes] :return: Solution. The Solution is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.flattenproperty.models.Solution :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_operations/_operations.py index 49c64d6790bb..0f8ac2448e4a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_flatten_property_put_flatten_model_request, build_flatten_property_put_flatten_read_only_model_request, @@ -38,7 +38,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import FlattenPropertyClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -65,12 +64,12 @@ async def put_flatten_model( @overload async def put_flatten_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.FlattenModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.FlattenModel: """put_flatten_model. :param input: Required. - :type input: JSON + :type input: ~specs.azure.clientgenerator.core.flattenproperty.types.FlattenModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -97,13 +96,13 @@ async def put_flatten_model( @distributed_trace_async async def put_flatten_model( - self, input: Union[_models.FlattenModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.FlattenModel, _types.FlattenModel, IO[bytes]], **kwargs: Any ) -> _models.FlattenModel: """put_flatten_model. - :param input: Is one of the following types: FlattenModel, JSON, IO[bytes] Required. - :type input: ~specs.azure.clientgenerator.core.flattenproperty.models.FlattenModel or JSON or - IO[bytes] + :param input: Is either a FlattenModel type or a IO[bytes] type. Required. + :type input: ~specs.azure.clientgenerator.core.flattenproperty.models.FlattenModel or + ~specs.azure.clientgenerator.core.flattenproperty.types.FlattenModel or IO[bytes] :return: FlattenModel. The FlattenModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.flattenproperty.models.FlattenModel :raises ~azure.core.exceptions.HttpResponseError: @@ -185,12 +184,12 @@ async def put_nested_flatten_model( @overload async def put_nested_flatten_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.NestedFlattenModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.NestedFlattenModel: """put_nested_flatten_model. :param input: Required. - :type input: JSON + :type input: ~specs.azure.clientgenerator.core.flattenproperty.types.NestedFlattenModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -217,13 +216,13 @@ async def put_nested_flatten_model( @distributed_trace_async async def put_nested_flatten_model( - self, input: Union[_models.NestedFlattenModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.NestedFlattenModel, _types.NestedFlattenModel, IO[bytes]], **kwargs: Any ) -> _models.NestedFlattenModel: """put_nested_flatten_model. - :param input: Is one of the following types: NestedFlattenModel, JSON, IO[bytes] Required. + :param input: Is either a NestedFlattenModel type or a IO[bytes] type. Required. :type input: ~specs.azure.clientgenerator.core.flattenproperty.models.NestedFlattenModel or - JSON or IO[bytes] + ~specs.azure.clientgenerator.core.flattenproperty.types.NestedFlattenModel or IO[bytes] :return: NestedFlattenModel. The NestedFlattenModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.flattenproperty.models.NestedFlattenModel :raises ~azure.core.exceptions.HttpResponseError: @@ -305,12 +304,12 @@ async def put_flatten_unknown_model( @overload async def put_flatten_unknown_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.FlattenUnknownModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.FlattenUnknownModel: """put_flatten_unknown_model. :param input: Required. - :type input: JSON + :type input: ~specs.azure.clientgenerator.core.flattenproperty.types.FlattenUnknownModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -337,13 +336,13 @@ async def put_flatten_unknown_model( @distributed_trace_async async def put_flatten_unknown_model( - self, input: Union[_models.FlattenUnknownModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.FlattenUnknownModel, _types.FlattenUnknownModel, IO[bytes]], **kwargs: Any ) -> _models.FlattenUnknownModel: """put_flatten_unknown_model. - :param input: Is one of the following types: FlattenUnknownModel, JSON, IO[bytes] Required. + :param input: Is either a FlattenUnknownModel type or a IO[bytes] type. Required. :type input: ~specs.azure.clientgenerator.core.flattenproperty.models.FlattenUnknownModel or - JSON or IO[bytes] + ~specs.azure.clientgenerator.core.flattenproperty.types.FlattenUnknownModel or IO[bytes] :return: FlattenUnknownModel. The FlattenUnknownModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.flattenproperty.models.FlattenUnknownModel :raises ~azure.core.exceptions.HttpResponseError: @@ -425,12 +424,12 @@ async def put_flatten_read_only_model( @overload async def put_flatten_read_only_model( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Solution, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Solution: """put_flatten_read_only_model. :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.flattenproperty.types.Solution :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -457,13 +456,13 @@ async def put_flatten_read_only_model( @distributed_trace_async async def put_flatten_read_only_model( - self, body: Union[_models.Solution, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.Solution, _types.Solution, IO[bytes]], **kwargs: Any ) -> _models.Solution: """put_flatten_read_only_model. - :param body: Is one of the following types: Solution, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.flattenproperty.models.Solution or JSON or - IO[bytes] + :param body: Is either a Solution type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.flattenproperty.models.Solution or + ~specs.azure.clientgenerator.core.flattenproperty.types.Solution or IO[bytes] :return: Solution. The Solution is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.flattenproperty.models.Solution :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/types.py index 2fe5da86c949..4af4d6265052 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-flatten-property/specs/azure/clientgenerator/core/flattenproperty/types.py @@ -16,7 +16,7 @@ class ChildFlattenModel(TypedDict, total=False): :ivar summary: Required. :vartype summary: str :ivar properties: Required. - :vartype properties: ~specs.azure.clientgenerator.core.flattenproperty.models.ChildModel + :vartype properties: "ChildModel" """ summary: Required[str] @@ -46,7 +46,7 @@ class FlattenModel(TypedDict, total=False): :ivar name: Required. :vartype name: str :ivar properties: Required. - :vartype properties: ~specs.azure.clientgenerator.core.flattenproperty.models.ChildModel + :vartype properties: "ChildModel" """ name: Required[str] @@ -61,7 +61,7 @@ class FlattenUnknownModel(TypedDict, total=False): :ivar name: Required. :vartype name: str :ivar properties: - :vartype properties: any + :vartype properties: Any """ name: Required[str] @@ -75,7 +75,7 @@ class NestedFlattenModel(TypedDict, total=False): :ivar name: Required. :vartype name: str :ivar properties: Required. - :vartype properties: ~specs.azure.clientgenerator.core.flattenproperty.models.ChildFlattenModel + :vartype properties: "ChildFlattenModel" """ name: Required[str] @@ -90,8 +90,7 @@ class Solution(TypedDict, total=False): :ivar name: Required. :vartype name: str :ivar properties: - :vartype properties: - ~specs.azure.clientgenerator.core.flattenproperty.models.SolutionProperties + :vartype properties: "SolutionProperties" """ name: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/dev_requirements.txt b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/dev_requirements.txt index 105486471444..0e53b6a72db5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/dev_requirements.txt +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/dev_requirements.txt @@ -1,3 +1,3 @@ --e ../../../tools/azure-sdk-tools +-e ../../../eng/tools/azure-sdk-tools ../../core/azure-core aiohttp \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/pyproject.toml index fa2658842282..c88cc7a70add 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/operations/_operations.py index 51dbcb711029..291e69d10764 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/operations/_operations.py @@ -26,7 +26,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -38,7 +38,6 @@ ) from .._configuration import HierarchyBuildingClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -78,12 +77,12 @@ async def update_pet_as_animal( @overload async def update_pet_as_animal( - self, animal: JSON, *, content_type: str = "application/json", **kwargs: Any + self, animal: _types.Animal, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Animal: """Update a pet as an animal. :param animal: Required. - :type animal: JSON + :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.types.Animal :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -110,13 +109,13 @@ async def update_pet_as_animal( @distributed_trace_async async def update_pet_as_animal( - self, animal: Union[_models.Animal, JSON, IO[bytes]], **kwargs: Any + self, animal: Union[_models.Animal, _types.Animal, IO[bytes]], **kwargs: Any ) -> _models.Animal: """Update a pet as an animal. - :param animal: Is one of the following types: Animal, JSON, IO[bytes] Required. - :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal or JSON or - IO[bytes] + :param animal: Is either a Animal type or a IO[bytes] type. Required. + :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal or + ~specs.azure.clientgenerator.core.hierarchybuilding.types.Animal or IO[bytes] :return: Animal. The Animal is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal :raises ~azure.core.exceptions.HttpResponseError: @@ -198,12 +197,12 @@ async def update_dog_as_animal( @overload async def update_dog_as_animal( - self, animal: JSON, *, content_type: str = "application/json", **kwargs: Any + self, animal: _types.Animal, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Animal: """Update a dog as an animal. :param animal: Required. - :type animal: JSON + :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.types.Animal :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -230,13 +229,13 @@ async def update_dog_as_animal( @distributed_trace_async async def update_dog_as_animal( - self, animal: Union[_models.Animal, JSON, IO[bytes]], **kwargs: Any + self, animal: Union[_models.Animal, _types.Animal, IO[bytes]], **kwargs: Any ) -> _models.Animal: """Update a dog as an animal. - :param animal: Is one of the following types: Animal, JSON, IO[bytes] Required. - :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal or JSON or - IO[bytes] + :param animal: Is either a Animal type or a IO[bytes] type. Required. + :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal or + ~specs.azure.clientgenerator.core.hierarchybuilding.types.Animal or IO[bytes] :return: Animal. The Animal is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal :raises ~azure.core.exceptions.HttpResponseError: @@ -336,12 +335,12 @@ async def update_pet_as_pet( @overload async def update_pet_as_pet( - self, pet: JSON, *, content_type: str = "application/json", **kwargs: Any + self, pet: _types.Pet, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pet: """Update a pet as a pet. :param pet: Required. - :type pet: JSON + :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.types.Pet :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -367,11 +366,12 @@ async def update_pet_as_pet( """ @distributed_trace_async - async def update_pet_as_pet(self, pet: Union[_models.Pet, JSON, IO[bytes]], **kwargs: Any) -> _models.Pet: + async def update_pet_as_pet(self, pet: Union[_models.Pet, _types.Pet, IO[bytes]], **kwargs: Any) -> _models.Pet: """Update a pet as a pet. - :param pet: Is one of the following types: Pet, JSON, IO[bytes] Required. - :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet or JSON or IO[bytes] + :param pet: Is either a Pet type or a IO[bytes] type. Required. + :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet or + ~specs.azure.clientgenerator.core.hierarchybuilding.types.Pet or IO[bytes] :return: Pet. The Pet is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet :raises ~azure.core.exceptions.HttpResponseError: @@ -453,12 +453,12 @@ async def update_dog_as_pet( @overload async def update_dog_as_pet( - self, pet: JSON, *, content_type: str = "application/json", **kwargs: Any + self, pet: _types.Pet, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pet: """Update a dog as a pet. :param pet: Required. - :type pet: JSON + :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.types.Pet :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -484,11 +484,12 @@ async def update_dog_as_pet( """ @distributed_trace_async - async def update_dog_as_pet(self, pet: Union[_models.Pet, JSON, IO[bytes]], **kwargs: Any) -> _models.Pet: + async def update_dog_as_pet(self, pet: Union[_models.Pet, _types.Pet, IO[bytes]], **kwargs: Any) -> _models.Pet: """Update a dog as a pet. - :param pet: Is one of the following types: Pet, JSON, IO[bytes] Required. - :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet or JSON or IO[bytes] + :param pet: Is either a Pet type or a IO[bytes] type. Required. + :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet or + ~specs.azure.clientgenerator.core.hierarchybuilding.types.Pet or IO[bytes] :return: Pet. The Pet is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet :raises ~azure.core.exceptions.HttpResponseError: @@ -588,12 +589,12 @@ async def update_dog_as_dog( @overload async def update_dog_as_dog( - self, dog: JSON, *, content_type: str = "application/json", **kwargs: Any + self, dog: _types.Dog, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Dog: """Update a dog as a dog. :param dog: Required. - :type dog: JSON + :type dog: ~specs.azure.clientgenerator.core.hierarchybuilding.types.Dog :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -619,11 +620,12 @@ async def update_dog_as_dog( """ @distributed_trace_async - async def update_dog_as_dog(self, dog: Union[_models.Dog, JSON, IO[bytes]], **kwargs: Any) -> _models.Dog: + async def update_dog_as_dog(self, dog: Union[_models.Dog, _types.Dog, IO[bytes]], **kwargs: Any) -> _models.Dog: """Update a dog as a dog. - :param dog: Is one of the following types: Dog, JSON, IO[bytes] Required. - :type dog: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Dog or JSON or IO[bytes] + :param dog: Is either a Dog type or a IO[bytes] type. Required. + :type dog: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Dog or + ~specs.azure.clientgenerator.core.hierarchybuilding.types.Dog or IO[bytes] :return: Dog. The Dog is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Dog :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/operations/_operations.py index 0386dcc69a1e..97b2e35bec2d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import HierarchyBuildingClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -159,12 +158,12 @@ def update_pet_as_animal( @overload def update_pet_as_animal( - self, animal: JSON, *, content_type: str = "application/json", **kwargs: Any + self, animal: _types.Animal, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Animal: """Update a pet as an animal. :param animal: Required. - :type animal: JSON + :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.types.Animal :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -190,12 +189,14 @@ def update_pet_as_animal( """ @distributed_trace - def update_pet_as_animal(self, animal: Union[_models.Animal, JSON, IO[bytes]], **kwargs: Any) -> _models.Animal: + def update_pet_as_animal( + self, animal: Union[_models.Animal, _types.Animal, IO[bytes]], **kwargs: Any + ) -> _models.Animal: """Update a pet as an animal. - :param animal: Is one of the following types: Animal, JSON, IO[bytes] Required. - :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal or JSON or - IO[bytes] + :param animal: Is either a Animal type or a IO[bytes] type. Required. + :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal or + ~specs.azure.clientgenerator.core.hierarchybuilding.types.Animal or IO[bytes] :return: Animal. The Animal is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal :raises ~azure.core.exceptions.HttpResponseError: @@ -277,12 +278,12 @@ def update_dog_as_animal( @overload def update_dog_as_animal( - self, animal: JSON, *, content_type: str = "application/json", **kwargs: Any + self, animal: _types.Animal, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Animal: """Update a dog as an animal. :param animal: Required. - :type animal: JSON + :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.types.Animal :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -308,12 +309,14 @@ def update_dog_as_animal( """ @distributed_trace - def update_dog_as_animal(self, animal: Union[_models.Animal, JSON, IO[bytes]], **kwargs: Any) -> _models.Animal: + def update_dog_as_animal( + self, animal: Union[_models.Animal, _types.Animal, IO[bytes]], **kwargs: Any + ) -> _models.Animal: """Update a dog as an animal. - :param animal: Is one of the following types: Animal, JSON, IO[bytes] Required. - :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal or JSON or - IO[bytes] + :param animal: Is either a Animal type or a IO[bytes] type. Required. + :type animal: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal or + ~specs.azure.clientgenerator.core.hierarchybuilding.types.Animal or IO[bytes] :return: Animal. The Animal is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Animal :raises ~azure.core.exceptions.HttpResponseError: @@ -412,11 +415,13 @@ def update_pet_as_pet( """ @overload - def update_pet_as_pet(self, pet: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Pet: + def update_pet_as_pet( + self, pet: _types.Pet, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Pet: """Update a pet as a pet. :param pet: Required. - :type pet: JSON + :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.types.Pet :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -442,11 +447,12 @@ def update_pet_as_pet( """ @distributed_trace - def update_pet_as_pet(self, pet: Union[_models.Pet, JSON, IO[bytes]], **kwargs: Any) -> _models.Pet: + def update_pet_as_pet(self, pet: Union[_models.Pet, _types.Pet, IO[bytes]], **kwargs: Any) -> _models.Pet: """Update a pet as a pet. - :param pet: Is one of the following types: Pet, JSON, IO[bytes] Required. - :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet or JSON or IO[bytes] + :param pet: Is either a Pet type or a IO[bytes] type. Required. + :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet or + ~specs.azure.clientgenerator.core.hierarchybuilding.types.Pet or IO[bytes] :return: Pet. The Pet is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet :raises ~azure.core.exceptions.HttpResponseError: @@ -527,11 +533,13 @@ def update_dog_as_pet( """ @overload - def update_dog_as_pet(self, pet: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Pet: + def update_dog_as_pet( + self, pet: _types.Pet, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Pet: """Update a dog as a pet. :param pet: Required. - :type pet: JSON + :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.types.Pet :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -557,11 +565,12 @@ def update_dog_as_pet( """ @distributed_trace - def update_dog_as_pet(self, pet: Union[_models.Pet, JSON, IO[bytes]], **kwargs: Any) -> _models.Pet: + def update_dog_as_pet(self, pet: Union[_models.Pet, _types.Pet, IO[bytes]], **kwargs: Any) -> _models.Pet: """Update a dog as a pet. - :param pet: Is one of the following types: Pet, JSON, IO[bytes] Required. - :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet or JSON or IO[bytes] + :param pet: Is either a Pet type or a IO[bytes] type. Required. + :type pet: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet or + ~specs.azure.clientgenerator.core.hierarchybuilding.types.Pet or IO[bytes] :return: Pet. The Pet is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Pet :raises ~azure.core.exceptions.HttpResponseError: @@ -660,11 +669,13 @@ def update_dog_as_dog( """ @overload - def update_dog_as_dog(self, dog: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Dog: + def update_dog_as_dog( + self, dog: _types.Dog, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Dog: """Update a dog as a dog. :param dog: Required. - :type dog: JSON + :type dog: ~specs.azure.clientgenerator.core.hierarchybuilding.types.Dog :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -690,11 +701,12 @@ def update_dog_as_dog( """ @distributed_trace - def update_dog_as_dog(self, dog: Union[_models.Dog, JSON, IO[bytes]], **kwargs: Any) -> _models.Dog: + def update_dog_as_dog(self, dog: Union[_models.Dog, _types.Dog, IO[bytes]], **kwargs: Any) -> _models.Dog: """Update a dog as a dog. - :param dog: Is one of the following types: Dog, JSON, IO[bytes] Required. - :type dog: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Dog or JSON or IO[bytes] + :param dog: Is either a Dog type or a IO[bytes] type. Required. + :type dog: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Dog or + ~specs.azure.clientgenerator.core.hierarchybuilding.types.Dog or IO[bytes] :return: Dog. The Dog is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.hierarchybuilding.models.Dog :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/types.py index d6daadc1e41b..c9ea3d12d7ae 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-hierarchy-building/specs/azure/clientgenerator/core/hierarchybuilding/types.py @@ -18,7 +18,7 @@ class Dog(TypedDict, total=False): :ivar trained: Whether the pet is trained. Required. :vartype trained: bool :ivar kind: Required. Default value is "dog". - :vartype kind: str + :vartype kind: Literal["dog"] :ivar breed: The breed of the dog. Required. :vartype breed: str """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/pyproject.toml index 1881e057f97c..8a9b270ef8ea 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-next-link-verb/specs/azure/clientgenerator/core/nextlinkverb/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/pyproject.toml index a4d03b43501a..c147bb81b235 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/CHANGELOG.md similarity index 53% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/CHANGELOG.md rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/LICENSE b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/LICENSE similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/LICENSE rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/LICENSE diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/MANIFEST.in b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/MANIFEST.in similarity index 78% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/MANIFEST.in rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/MANIFEST.in index 8a97fb919767..df1e3b50ef70 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/MANIFEST.in +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/MANIFEST.in @@ -1,6 +1,6 @@ include *.md include LICENSE -include specs/azure/clientgenerator/core/clientinitialization/py.typed +include specs/azure/clientgenerator/core/responseasbool/py.typed recursive-include tests *.py recursive-include samples *.py *.md include specs/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/README.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/_metadata.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/_metadata.json new file mode 100644 index 000000000000..49515fdbafdf --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/_metadata.json @@ -0,0 +1,3 @@ +{ + "apiVersions": {} +} \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/apiview-properties.json new file mode 100644 index 000000000000..a7bcc0bd73fb --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/apiview-properties.json @@ -0,0 +1,10 @@ +{ + "CrossLanguagePackageId": "_Specs_.Azure.ClientGenerator.Core.ResponseAsBool", + "CrossLanguageDefinitionId": { + "specs.azure.clientgenerator.core.responseasbool.operations.HeadAsBooleanOperations.exists": "_Specs_.Azure.ClientGenerator.Core.ResponseAsBool.HeadAsBoolean.exists", + "specs.azure.clientgenerator.core.responseasbool.aio.operations.HeadAsBooleanOperations.exists": "_Specs_.Azure.ClientGenerator.Core.ResponseAsBool.HeadAsBoolean.exists", + "specs.azure.clientgenerator.core.responseasbool.operations.HeadAsBooleanOperations.not_exists": "_Specs_.Azure.ClientGenerator.Core.ResponseAsBool.HeadAsBoolean.notExists", + "specs.azure.clientgenerator.core.responseasbool.aio.operations.HeadAsBooleanOperations.not_exists": "_Specs_.Azure.ClientGenerator.Core.ResponseAsBool.HeadAsBoolean.notExists" + }, + "CrossLanguageVersion": "57f7b0b65ebf" +} \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/dev_requirements.txt b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/dev_requirements.txt similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/dev_requirements.txt rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/dev_requirements.txt diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/conftest.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/conftest.py new file mode 100644 index 000000000000..461260e948d2 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/conftest.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + responseasbool_subscription_id = os.environ.get( + "RESPONSEASBOOL_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + responseasbool_tenant_id = os.environ.get("RESPONSEASBOOL_TENANT_ID", "00000000-0000-0000-0000-000000000000") + responseasbool_client_id = os.environ.get("RESPONSEASBOOL_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + responseasbool_client_secret = os.environ.get( + "RESPONSEASBOOL_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=responseasbool_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=responseasbool_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=responseasbool_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=responseasbool_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_multiple_params.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/test_response_as_bool_head_as_boolean_operations.py similarity index 57% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_multiple_params.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/test_response_as_bool_head_as_boolean_operations.py index 92b624f15bf9..ad85ff916d3e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_multiple_params.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/test_response_as_bool_head_as_boolean_operations.py @@ -7,29 +7,25 @@ # -------------------------------------------------------------------------- import pytest from devtools_testutils import recorded_by_proxy -from testpreparer import MultipleParamsClientTestBase, MultipleParamsPreparer +from testpreparer import ResponseAsBoolClientTestBase, ResponseAsBoolPreparer @pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestMultipleParams(MultipleParamsClientTestBase): - @MultipleParamsPreparer() +class TestResponseAsBoolHeadAsBooleanOperations(ResponseAsBoolClientTestBase): + @ResponseAsBoolPreparer() @recorded_by_proxy - def test_with_query(self, multipleparams_endpoint): - client = self.create_client(endpoint=multipleparams_endpoint) - response = client.with_query( - id="str", - ) + def test_head_as_boolean_exists(self, responseasbool_endpoint): + client = self.create_client(endpoint=responseasbool_endpoint) + response = client.head_as_boolean.exists() # please add some check logic here by yourself # ... - @MultipleParamsPreparer() + @ResponseAsBoolPreparer() @recorded_by_proxy - def test_with_body(self, multipleparams_endpoint): - client = self.create_client(endpoint=multipleparams_endpoint) - response = client.with_body( - body={"name": "str"}, - ) + def test_head_as_boolean_not_exists(self, responseasbool_endpoint): + client = self.create_client(endpoint=responseasbool_endpoint) + response = client.head_as_boolean.not_exists() # please add some check logic here by yourself # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_multiple_params_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/test_response_as_bool_head_as_boolean_operations_async.py similarity index 54% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_multiple_params_async.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/test_response_as_bool_head_as_boolean_operations_async.py index 14ef35169bc4..9118b9fca216 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_multiple_params_async.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/test_response_as_bool_head_as_boolean_operations_async.py @@ -7,30 +7,26 @@ # -------------------------------------------------------------------------- import pytest from devtools_testutils.aio import recorded_by_proxy_async -from testpreparer import MultipleParamsPreparer -from testpreparer_async import MultipleParamsClientTestBaseAsync +from testpreparer import ResponseAsBoolPreparer +from testpreparer_async import ResponseAsBoolClientTestBaseAsync @pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestMultipleParamsAsync(MultipleParamsClientTestBaseAsync): - @MultipleParamsPreparer() +class TestResponseAsBoolHeadAsBooleanOperationsAsync(ResponseAsBoolClientTestBaseAsync): + @ResponseAsBoolPreparer() @recorded_by_proxy_async - async def test_with_query(self, multipleparams_endpoint): - client = self.create_async_client(endpoint=multipleparams_endpoint) - response = await client.with_query( - id="str", - ) + async def test_head_as_boolean_exists(self, responseasbool_endpoint): + client = self.create_async_client(endpoint=responseasbool_endpoint) + response = await client.head_as_boolean.exists() # please add some check logic here by yourself # ... - @MultipleParamsPreparer() + @ResponseAsBoolPreparer() @recorded_by_proxy_async - async def test_with_body(self, multipleparams_endpoint): - client = self.create_async_client(endpoint=multipleparams_endpoint) - response = await client.with_body( - body={"name": "str"}, - ) + async def test_head_as_boolean_not_exists(self, responseasbool_endpoint): + client = self.create_async_client(endpoint=responseasbool_endpoint) + response = await client.head_as_boolean.not_exists() # please add some check logic here by yourself # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/testpreparer.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/testpreparer.py new file mode 100644 index 000000000000..af32cf86e771 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/testpreparer.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer +import functools +from specs.azure.clientgenerator.core.responseasbool import ResponseAsBoolClient + + +class ResponseAsBoolClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(ResponseAsBoolClient) + return self.create_client_from_credential( + ResponseAsBoolClient, + credential=credential, + endpoint=endpoint, + ) + + +ResponseAsBoolPreparer = functools.partial( + PowerShellPreparer, "responseasbool", responseasbool_endpoint="https://fake_responseasbool_endpoint.com" +) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/testpreparer_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/testpreparer_async.py new file mode 100644 index 000000000000..237740f43b5c --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/generated_tests/testpreparer_async.py @@ -0,0 +1,20 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from devtools_testutils import AzureRecordedTestCase +from specs.azure.clientgenerator.core.responseasbool.aio import ResponseAsBoolClient + + +class ResponseAsBoolClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(ResponseAsBoolClient, is_async=True) + return self.create_client_from_credential( + ResponseAsBoolClient, + credential=credential, + endpoint=endpoint, + ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/pyproject.toml similarity index 85% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/pyproject.toml rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/pyproject.toml index 58b5e49608a7..cdbb19317b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/pyproject.toml @@ -10,24 +10,24 @@ requires = ["setuptools>=77.0.3", "wheel"] build-backend = "setuptools.build_meta" [project] -name = "specs-azure-clientgenerator-core-clientinitialization" +name = "specs-azure-clientgenerator-core-responseasbool" authors = [ { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, ] -description = "Microsoft Corporation Azure Specs Azure Clientgenerator Core Clientinitialization Client Library for Python" +description = "Microsoft Corporation Azure Specs Azure Clientgenerator Core Responseasbool Client Library for Python" license = "MIT" classifiers = [ "Development Status :: 4 - Beta", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] -requires-python = ">=3.9" +requires-python = ">=3.10" keywords = ["azure", "azure sdk"] dependencies = [ @@ -43,7 +43,7 @@ dynamic = [ repository = "https://github.com/Azure/azure-sdk-for-python" [tool.setuptools.dynamic] -version = {attr = "specs.azure.clientgenerator.core.clientinitialization._version.VERSION"} +version = {attr = "specs.azure.clientgenerator.core.responseasbool._version.VERSION"} readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} [tool.setuptools.packages.find] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/__init__.py new file mode 100644 index 000000000000..ad58a5fdaced --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ResponseAsBoolClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ResponseAsBoolClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_client.py new file mode 100644 index 000000000000..eff428e111af --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_client.py @@ -0,0 +1,101 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +import sys +from typing import Any + +from azure.core import PipelineClient +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse + +from ._configuration import ResponseAsBoolClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .headasboolean.operations import HeadAsBooleanOperations + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + + +class ResponseAsBoolClient: # pylint: disable=client-accepts-api-version-keyword + """Test for @responseAsBool decorator. + + :ivar head_as_boolean: HeadAsBooleanOperations operations + :vartype head_as_boolean: + specs.azure.clientgenerator.core.responseasbool.operations.HeadAsBooleanOperations + :keyword endpoint: Service host. Default value is "http://localhost:3000". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "http://localhost:3000", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = ResponseAsBoolClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.head_as_boolean = HeadAsBooleanOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_configuration.py new file mode 100644 index 000000000000..66ce6359c7a9 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_configuration.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any + +from azure.core.pipeline import policies + +from ._version import VERSION + + +class ResponseAsBoolClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ResponseAsBoolClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "http://localhost:3000". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-responseasbool/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_utils/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_utils/__init__.py similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_utils/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_utils/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_utils/model_base.py similarity index 69% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_utils/model_base.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_utils/model_base.py index c402af2afc63..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_utils/model_base.py @@ -23,14 +23,19 @@ from json import JSONEncoder import xml.etree.ElementTree as ET from collections.abc import MutableMapping -from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError from azure.core import CaseInsensitiveEnumMeta from azure.core.pipeline import PipelineResponse from azure.core.serialization import _Null + from azure.core.rest import HttpResponse +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _LOGGER = logging.getLogger(__name__) __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] @@ -104,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -296,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -325,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -420,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -444,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -479,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -504,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -515,6 +554,8 @@ def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: return self._data.setdefault(key, default) def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data try: other_model = self.__class__(other) except Exception: @@ -557,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass @@ -583,6 +624,239 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin return _serialize(value, rf._format) +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param class Model(_MyMutableMapping): _is_model = True # label whether current class's _attr_to_rest_field has been calculated @@ -593,59 +867,10 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: class_name = self.__class__.__name__ if len(args) > 1: raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") - dict_to_pass = { - rest_field._rest_name: rest_field._default - for rest_field in self._attr_to_rest_field.values() - if rest_field._default is not _UNSET - } - if args: # pylint: disable=too-many-nested-blocks + dict_to_pass: dict[str, typing.Any] = {} + if args: if isinstance(args[0], ET.Element): - existed_attr_keys = [] - model_meta = getattr(self, "_xml", {}) - - for rf in self._attr_to_rest_field.values(): - prop_meta = getattr(rf, "_xml", {}) - xml_name = prop_meta.get("name", rf._rest_name) - xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - # attribute - if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) - continue - - # unwrapped element is array - if prop_meta.get("unwrapped", False): - # unwrapped array could either use prop items meta/prop meta - if prop_meta.get("itemsName"): - xml_name = prop_meta.get("itemsName") - xml_ns = prop_meta.get("itemNs") - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - items = args[0].findall(xml_name) # pyright: ignore - if len(items) > 0: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) - continue - - # text element is primitive type - if prop_meta.get("text", False): - if args[0].text is not None: - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) - continue - - # wrapped element could be normal property or array, it should only have one element - item = args[0].find(xml_name) - if item is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) - - # rest thing is additional properties - for e in args[0]: - if e.tag not in existed_attr_keys: - dict_to_pass[e.tag] = _convert_element(e) + dict_to_pass.update(self._init_from_xml(args[0])) else: dict_to_pass.update( {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} @@ -662,8 +887,117 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if v is not None } ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) super().__init__(dict_to_pass) + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + self, element: ET.Element + ) -> dict[str, typing.Any]: + """Deserialize an XML element into a dict mapping rest field names to values. + + :param ET.Element element: The XML element to deserialize from. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + existed_attr_keys: list[str] = [] + + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + def copy(self) -> "Model": return Model(self.__dict__) @@ -688,6 +1022,9 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -716,7 +1053,7 @@ def _deserialize(cls, data, exist_discriminators): model_meta = getattr(cls, "_xml", {}) prop_meta = getattr(discriminator, "_xml", {}) xml_name = prop_meta.get("name", discriminator._rest_name) - xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) if xml_ns: xml_name = "{" + xml_ns + "}" + xml_name @@ -889,6 +1226,8 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore @@ -981,16 +1320,20 @@ def _deserialize_with_callable( return float(value.text) if value.text else None if deserializer is bool: return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None if deserializer is None: return value if deserializer in [int, float, bool]: return deserializer(value) if isinstance(deserializer, CaseInsensitiveEnumMeta): try: - return deserializer(value) + return deserializer(value.text if isinstance(value, ET.Element) else value) except ValueError: # for unknown value, return raw value - return value + return value.text if isinstance(value, ET.Element) else value if isinstance(deserializer, type) and issubclass(deserializer, Model): return deserializer._deserialize(value, []) return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) @@ -1043,6 +1386,7 @@ def _failsafe_deserialize_xml( return None +# pylint: disable=too-many-instance-attributes class _RestField: def __init__( self, @@ -1055,6 +1399,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, ): self._type = type self._rest_name_input = name @@ -1062,10 +1407,12 @@ def __init__( self._is_discriminator = is_discriminator self._visibility = visibility self._is_model = False + self._is_optional = False self._default = default self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._deserializer = deserializer @property def _class_type(self) -> typing.Any: @@ -1085,7 +1432,10 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class # Use _data.get() directly to avoid triggering __getitem__ which clears the cache - item = obj._data.get(self._rest_name) + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None if item is None: return item if self._is_model: @@ -1098,7 +1448,11 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # Return the value from _data directly (it's been deserialized in place) return obj._data.get(self._rest_name) - deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) # For mutable types, store the deserialized value back in _data # so mutations directly affect _data @@ -1144,6 +1498,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, ) -> typing.Any: return _RestField( name=name, @@ -1153,6 +1508,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + deserializer=deserializer, ) @@ -1177,6 +1533,56 @@ def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + def _get_element( o: typing.Any, exclude_readonly: bool = False, @@ -1188,10 +1594,16 @@ def _get_element( # if prop is a model, then use the prop element directly, else generate a wrapper of model if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) wrapped_element = _create_xml_element( - model_meta.get("name", o.__class__.__name__), + element_name, model_meta.get("prefix"), - model_meta.get("ns"), + _model_ns, ) readonly_props = [] @@ -1213,7 +1625,9 @@ def _get_element( # additional properties will not have rest field, use the wire name as xml name prop_meta = {"name": k} - # if no ns for prop, use model's + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. if prop_meta.get("ns") is None and model_meta.get("ns"): prop_meta["ns"] = model_meta.get("ns") prop_meta["prefix"] = model_meta.get("prefix") @@ -1225,12 +1639,7 @@ def _get_element( # text could only set on primitive type wrapped_element.text = _get_primitive_type_value(v) elif prop_meta.get("attribute", False): - xml_name = prop_meta.get("name", k) - if prop_meta.get("ns"): - ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore - xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore - # attribute should be primitive type - wrapped_element.set(xml_name, _get_primitive_type_value(v)) + _set_xml_attribute(wrapped_element, k, v, prop_meta) else: # other wrapped prop element wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) @@ -1239,6 +1648,7 @@ def _get_element( return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore if isinstance(o, dict): result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None for k, v in o.items(): result.append( _get_wrapped_element( @@ -1246,7 +1656,7 @@ def _get_element( exclude_readonly, { "name": k, - "ns": parent_meta.get("ns") if parent_meta else None, + "ns": _dict_ns, "prefix": parent_meta.get("prefix") if parent_meta else None, }, ) @@ -1255,13 +1665,16 @@ def _get_element( # primitive case need to create element based on parent_meta if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) return _get_wrapped_element( o, exclude_readonly, { "name": parent_meta.get("itemsName", parent_meta.get("name")), "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), - "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + "ns": _items_ns, }, ) @@ -1273,8 +1686,9 @@ def _get_wrapped_element( exclude_readonly: bool, meta: typing.Optional[dict[str, typing.Any]], ) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None wrapped_element = _create_xml_element( - meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns ) if isinstance(v, (dict, list)): wrapped_element.extend(_get_element(v, exclude_readonly, meta)) @@ -1295,11 +1709,29 @@ def _get_primitive_type_value(v) -> str: return str(v) +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + def _create_xml_element( tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None ) -> ET.Element: if prefix and ns: - ET.register_namespace(prefix, ns) + _safe_register_namespace(prefix, ns) if ns: return ET.Element("{" + ns + "}" + tag) return ET.Element(tag) @@ -1310,6 +1742,8 @@ def _deserialize_xml( value: str, ) -> typing.Any: element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) return _deserialize(deserializer, element) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_utils/serialization.py similarity index 93% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_utils/serialization.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_utils/serialization.py index 81ec1de5922b..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_utils/serialization.py @@ -39,11 +39,15 @@ import xml.etree.ElementTree as ET import isodate # type: ignore -from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") JSON = MutableMapping[str, Any] @@ -516,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1105,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1377,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1389,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1401,7 +1472,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: # Otherwise, result are unexpected self.additional_properties_detection = True - def __call__(self, target_obj, response_data, content_type=None): + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements """Call the deserializer to process a REST response. :param str target_obj: Target data type to deserialize to. @@ -1411,6 +1482,27 @@ def __call__(self, target_obj, response_data, content_type=None): :return: Deserialized object. :rtype: object """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) @@ -1929,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_version.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_version.py similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_version.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/_version.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/__init__.py new file mode 100644 index 000000000000..45ccfc98b635 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ResponseAsBoolClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ResponseAsBoolClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/_client.py new file mode 100644 index 000000000000..57ef3aee90e9 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/_client.py @@ -0,0 +1,103 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +import sys +from typing import Any, Awaitable + +from azure.core import AsyncPipelineClient +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest + +from .._utils.serialization import Deserializer, Serializer +from ..headasboolean.aio.operations import HeadAsBooleanOperations +from ._configuration import ResponseAsBoolClientConfiguration + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + + +class ResponseAsBoolClient: # pylint: disable=client-accepts-api-version-keyword + """Test for @responseAsBool decorator. + + :ivar head_as_boolean: HeadAsBooleanOperations operations + :vartype head_as_boolean: + specs.azure.clientgenerator.core.responseasbool.aio.operations.HeadAsBooleanOperations + :keyword endpoint: Service host. Default value is "http://localhost:3000". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "http://localhost:3000", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = ResponseAsBoolClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.head_as_boolean = HeadAsBooleanOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/_configuration.py new file mode 100644 index 000000000000..a27165709e47 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/_configuration.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any + +from azure.core.pipeline import policies + +from .._version import VERSION + + +class ResponseAsBoolClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ResponseAsBoolClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "http://localhost:3000". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "specs-azure-clientgenerator-core-responseasbool/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/operations/__init__.py new file mode 100644 index 000000000000..7540f96aa4c6 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import HeadAsBooleanOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "HeadAsBooleanOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/operations/_operations.py new file mode 100644 index 000000000000..59493740af79 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/operations/_operations.py @@ -0,0 +1,137 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async + +from ...._utils.serialization import Deserializer, Serializer +from ....aio._configuration import ResponseAsBoolClientConfiguration +from ...operations._operations import build_head_as_boolean_exists_request, build_head_as_boolean_not_exists_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class HeadAsBooleanOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~specs.azure.clientgenerator.core.responseasbool.aio.ResponseAsBoolClient`'s + :attr:`head_as_boolean` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ResponseAsBoolClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def exists(self, **kwargs: Any) -> bool: + """exists. + + :return: bool + :rtype: bool + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_head_as_boolean_exists_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + return 200 <= response.status_code <= 299 + + @distributed_trace_async + async def not_exists(self, **kwargs: Any) -> bool: + """not_exists. + + :return: bool + :rtype: bool + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_head_as_boolean_not_exists_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + return 200 <= response.status_code <= 299 diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/operations/__init__.py new file mode 100644 index 000000000000..7540f96aa4c6 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import HeadAsBooleanOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "HeadAsBooleanOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/operations/_operations.py new file mode 100644 index 000000000000..b7ada803845c --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/operations/_operations.py @@ -0,0 +1,153 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace + +from ..._configuration import ResponseAsBoolClientConfiguration +from ..._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_head_as_boolean_exists_request(**kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/azure/client-generator-core/response-as-bool/exists" + + return HttpRequest(method="HEAD", url=_url, **kwargs) + + +def build_head_as_boolean_not_exists_request(**kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/azure/client-generator-core/response-as-bool/exists/not-exists" + + return HttpRequest(method="HEAD", url=_url, **kwargs) + + +class HeadAsBooleanOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~specs.azure.clientgenerator.core.responseasbool.ResponseAsBoolClient`'s + :attr:`head_as_boolean` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ResponseAsBoolClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def exists(self, **kwargs: Any) -> bool: + """exists. + + :return: bool + :rtype: bool + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_head_as_boolean_exists_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + return 200 <= response.status_code <= 299 + + @distributed_trace + def not_exists(self, **kwargs: Any) -> bool: + """not_exists. + + :return: bool + :rtype: bool + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_head_as_boolean_not_exists_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204, 404]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + return 200 <= response.status_code <= 299 diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/headasboolean/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/py.typed b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/py.typed similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/py.typed rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-response-as-bool/specs/azure/clientgenerator/core/responseasbool/py.typed diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/apiview-properties.json index 890152c06346..a0d36c5ae3f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/apiview-properties.json +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/apiview-properties.json @@ -2,6 +2,8 @@ "CrossLanguagePackageId": "_Specs_.Azure.ClientGenerator.Core.Usage", "CrossLanguageDefinitionId": { "specs.azure.clientgenerator.core.usage.models.InputModel": "_Specs_.Azure.ClientGenerator.Core.Usage.ModelInOperation.InputModel", + "specs.azure.clientgenerator.core.usage.models.NamespaceModel": "_Specs_.Azure.ClientGenerator.Core.Usage.Models.NamespaceModel", + "specs.azure.clientgenerator.core.usage.models.NestedNamespaceModel": "_Specs_.Azure.ClientGenerator.Core.Usage.Models.Nested.NestedNamespaceModel", "specs.azure.clientgenerator.core.usage.models.OrphanModel": "_Specs_.Azure.ClientGenerator.Core.Usage.OrphanModel", "specs.azure.clientgenerator.core.usage.models.OutputModel": "_Specs_.Azure.ClientGenerator.Core.Usage.ModelInOperation.OutputModel", "specs.azure.clientgenerator.core.usage.models.ResultModel": "_Specs_.Azure.ClientGenerator.Core.Usage.ModelInOperation.ResultModel", @@ -13,7 +15,9 @@ "specs.azure.clientgenerator.core.usage.operations.ModelInOperationOperations.model_in_read_only_property": "_Specs_.Azure.ClientGenerator.Core.Usage.ModelInOperation.modelInReadOnlyProperty", "specs.azure.clientgenerator.core.usage.aio.operations.ModelInOperationOperations.model_in_read_only_property": "_Specs_.Azure.ClientGenerator.Core.Usage.ModelInOperation.modelInReadOnlyProperty", "specs.azure.clientgenerator.core.usage.operations.ModelInOperationOperations.orphan_model_serializable": "_Specs_.Azure.ClientGenerator.Core.Usage.ModelInOperation.orphanModelSerializable", - "specs.azure.clientgenerator.core.usage.aio.operations.ModelInOperationOperations.orphan_model_serializable": "_Specs_.Azure.ClientGenerator.Core.Usage.ModelInOperation.orphanModelSerializable" + "specs.azure.clientgenerator.core.usage.aio.operations.ModelInOperationOperations.orphan_model_serializable": "_Specs_.Azure.ClientGenerator.Core.Usage.ModelInOperation.orphanModelSerializable", + "specs.azure.clientgenerator.core.usage.operations.NamespaceUsageOperations.namespace_model_serializable": "_Specs_.Azure.ClientGenerator.Core.Usage.NamespaceUsage.namespaceModelSerializable", + "specs.azure.clientgenerator.core.usage.aio.operations.NamespaceUsageOperations.namespace_model_serializable": "_Specs_.Azure.ClientGenerator.Core.Usage.NamespaceUsage.namespaceModelSerializable" }, - "CrossLanguageVersion": "fa69fb13e4f3" + "CrossLanguageVersion": "1443e84b75d8" } \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/generated_tests/test_usage_namespace_usage_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/generated_tests/test_usage_namespace_usage_operations.py new file mode 100644 index 000000000000..31ef60551865 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/generated_tests/test_usage_namespace_usage_operations.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import UsageClientTestBase, UsagePreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestUsageNamespaceUsageOperations(UsageClientTestBase): + @UsagePreparer() + @recorded_by_proxy + def test_namespace_usage_namespace_model_serializable(self, usage_endpoint): + client = self.create_client(endpoint=usage_endpoint) + response = client.namespace_usage.namespace_model_serializable( + body={}, + content_type="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/generated_tests/test_usage_namespace_usage_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/generated_tests/test_usage_namespace_usage_operations_async.py new file mode 100644 index 000000000000..04d1df11d01e --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/generated_tests/test_usage_namespace_usage_operations_async.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import UsagePreparer +from testpreparer_async import UsageClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestUsageNamespaceUsageOperationsAsync(UsageClientTestBaseAsync): + @UsagePreparer() + @recorded_by_proxy_async + async def test_namespace_usage_namespace_model_serializable(self, usage_endpoint): + client = self.create_async_client(endpoint=usage_endpoint) + response = await client.namespace_usage.namespace_model_serializable( + body={}, + content_type="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/pyproject.toml index 14a791298b72..466b882c69b8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_client.py index f196d51a2121..b2f0881e7119 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_client.py @@ -16,7 +16,7 @@ from ._configuration import UsageClientConfiguration from ._utils.serialization import Deserializer, Serializer -from .operations import ModelInOperationOperations +from .operations import ModelInOperationOperations, NamespaceUsageOperations if sys.version_info >= (3, 11): from typing import Self @@ -30,6 +30,9 @@ class UsageClient: # pylint: disable=client-accepts-api-version-keyword :ivar model_in_operation: ModelInOperationOperations operations :vartype model_in_operation: specs.azure.clientgenerator.core.usage.operations.ModelInOperationOperations + :ivar namespace_usage: NamespaceUsageOperations operations + :vartype namespace_usage: + specs.azure.clientgenerator.core.usage.operations.NamespaceUsageOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -65,6 +68,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self.model_in_operation = ModelInOperationOperations( self._client, self._config, self._serialize, self._deserialize ) + self.namespace_usage = NamespaceUsageOperations(self._client, self._config, self._serialize, self._deserialize) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/_client.py index c6eaeceec6c6..8b33676439d3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/_client.py @@ -16,7 +16,7 @@ from .._utils.serialization import Deserializer, Serializer from ._configuration import UsageClientConfiguration -from .operations import ModelInOperationOperations +from .operations import ModelInOperationOperations, NamespaceUsageOperations if sys.version_info >= (3, 11): from typing import Self @@ -30,6 +30,9 @@ class UsageClient: # pylint: disable=client-accepts-api-version-keyword :ivar model_in_operation: ModelInOperationOperations operations :vartype model_in_operation: specs.azure.clientgenerator.core.usage.aio.operations.ModelInOperationOperations + :ivar namespace_usage: NamespaceUsageOperations operations + :vartype namespace_usage: + specs.azure.clientgenerator.core.usage.aio.operations.NamespaceUsageOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -65,6 +68,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self.model_in_operation = ModelInOperationOperations( self._client, self._config, self._serialize, self._deserialize ) + self.namespace_usage = NamespaceUsageOperations(self._client, self._config, self._serialize, self._deserialize) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/__init__.py index 9a46cfc7af85..94fbf98448fb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/__init__.py @@ -13,6 +13,7 @@ from ._patch import * # pylint: disable=unused-wildcard-import from ._operations import ModelInOperationOperations # type: ignore +from ._operations import NamespaceUsageOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -20,6 +21,7 @@ __all__ = [ "ModelInOperationOperations", + "NamespaceUsageOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/_operations.py index 2ea448fe57f3..3133dccb5d1f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/_operations.py @@ -26,7 +26,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -34,10 +34,10 @@ build_model_in_operation_model_in_read_only_property_request, build_model_in_operation_orphan_model_serializable_request, build_model_in_operation_output_to_input_output_request, + build_namespace_usage_namespace_model_serializable_request, ) from .._configuration import UsageClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -69,7 +69,7 @@ async def input_to_input_output( { "name": "Madge" - }. + } :param body: Required. :type body: ~specs.azure.clientgenerator.core.usage.models.InputModel @@ -82,17 +82,19 @@ async def input_to_input_output( """ @overload - async def input_to_input_output(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def input_to_input_output( + self, body: _types.InputModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Expected body parameter: .. code-block:: json { "name": "Madge" - }. + } :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.usage.types.InputModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -111,7 +113,7 @@ async def input_to_input_output( { "name": "Madge" - }. + } :param body: Required. :type body: IO[bytes] @@ -124,17 +126,20 @@ async def input_to_input_output( """ @distributed_trace_async - async def input_to_input_output(self, body: Union[_models.InputModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def input_to_input_output( + self, body: Union[_models.InputModel, _types.InputModel, IO[bytes]], **kwargs: Any + ) -> None: """Expected body parameter: .. code-block:: json { "name": "Madge" - }. + } - :param body: Is one of the following types: InputModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.usage.models.InputModel or JSON or IO[bytes] + :param body: Is either a InputModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.usage.models.InputModel or + ~specs.azure.clientgenerator.core.usage.types.InputModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -193,7 +198,7 @@ async def output_to_input_output(self, **kwargs: Any) -> _models.OutputModel: { "name": "Madge" - }. + } :return: OutputModel. The OutputModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.usage.models.OutputModel @@ -269,7 +274,7 @@ async def model_in_read_only_property( "result": { "name": "Madge" } - }. + } :param body: Required. :type body: ~specs.azure.clientgenerator.core.usage.models.RoundTripModel @@ -283,7 +288,7 @@ async def model_in_read_only_property( @overload async def model_in_read_only_property( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.RoundTripModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.RoundTripModel: """ "ResultModel" should be usage=output, as it is read-only and does not exist in request body. @@ -302,10 +307,10 @@ async def model_in_read_only_property( "result": { "name": "Madge" } - }. + } :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.usage.types.RoundTripModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -335,7 +340,7 @@ async def model_in_read_only_property( "result": { "name": "Madge" } - }. + } :param body: Required. :type body: IO[bytes] @@ -349,7 +354,7 @@ async def model_in_read_only_property( @distributed_trace_async async def model_in_read_only_property( - self, body: Union[_models.RoundTripModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.RoundTripModel, _types.RoundTripModel, IO[bytes]], **kwargs: Any ) -> _models.RoundTripModel: """ "ResultModel" should be usage=output, as it is read-only and does not exist in request body. @@ -368,10 +373,11 @@ async def model_in_read_only_property( "result": { "name": "Madge" } - }. + } - :param body: Is one of the following types: RoundTripModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.usage.models.RoundTripModel or JSON or IO[bytes] + :param body: Is either a RoundTripModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.usage.models.RoundTripModel or + ~specs.azure.clientgenerator.core.usage.types.RoundTripModel or IO[bytes] :return: RoundTripModel. The RoundTripModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.usage.models.RoundTripModel :raises ~azure.core.exceptions.HttpResponseError: @@ -446,7 +452,7 @@ async def orphan_model_serializable(self, body: Any, **kwargs: Any) -> None: { "name": "name", "desc": "desc" - }. + } :param body: Required. :type body: any @@ -494,3 +500,80 @@ async def orphan_model_serializable(self, body: Any, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore + + +class NamespaceUsageOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~specs.azure.clientgenerator.core.usage.aio.UsageClient`'s + :attr:`namespace_usage` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: UsageClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def namespace_model_serializable(self, body: Any, **kwargs: Any) -> None: + """Serialize the 'NamespaceModel' as request body. + + Expected body parameter: + + .. code-block:: json + + { + "name": "test" + } + + :param body: Required. + :type body: any + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_namespace_usage_namespace_model_serializable_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/__init__.py index e5ed72eb8fc8..79fc02cef3bc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/__init__.py @@ -15,6 +15,8 @@ from ._models import ( # type: ignore InputModel, + NamespaceModel, + NestedNamespaceModel, OrphanModel, OutputModel, ResultModel, @@ -26,6 +28,8 @@ __all__ = [ "InputModel", + "NamespaceModel", + "NestedNamespaceModel", "OrphanModel", "OutputModel", "ResultModel", diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/_models.py index 79676ce729b4..86762d410987 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/_models.py @@ -43,6 +43,62 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class NamespaceModel(_Model): + """NamespaceModel. + + :ivar name: Required. + :vartype name: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NestedNamespaceModel(_Model): + """NestedNamespaceModel. + + :ivar value: Required. + :vartype value: str + """ + + value: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + value: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class OrphanModel(_Model): """Not used anywhere, but access is override to public so still need to be generated and exported with serialization. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/__init__.py index 9a46cfc7af85..94fbf98448fb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/__init__.py @@ -13,6 +13,7 @@ from ._patch import * # pylint: disable=unused-wildcard-import from ._operations import ModelInOperationOperations # type: ignore +from ._operations import NamespaceUsageOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -20,6 +21,7 @@ __all__ = [ "ModelInOperationOperations", + "NamespaceUsageOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/_operations.py index a9b04b1c0147..83162e244857 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import UsageClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -105,6 +104,21 @@ def build_model_in_operation_orphan_model_serializable_request( # pylint: disab return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) +def build_namespace_usage_namespace_model_serializable_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: str = kwargs.pop("content_type") + # Construct URL + _url = "/azure/client-generator-core/usage/namespaceModelSerializable" + + # Construct headers + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + class ModelInOperationOperations: """ .. warning:: @@ -132,7 +146,7 @@ def input_to_input_output( { "name": "Madge" - }. + } :param body: Required. :type body: ~specs.azure.clientgenerator.core.usage.models.InputModel @@ -145,17 +159,19 @@ def input_to_input_output( """ @overload - def input_to_input_output(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def input_to_input_output( + self, body: _types.InputModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Expected body parameter: .. code-block:: json { "name": "Madge" - }. + } :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.usage.types.InputModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -172,7 +188,7 @@ def input_to_input_output(self, body: IO[bytes], *, content_type: str = "applica { "name": "Madge" - }. + } :param body: Required. :type body: IO[bytes] @@ -186,7 +202,7 @@ def input_to_input_output(self, body: IO[bytes], *, content_type: str = "applica @distributed_trace def input_to_input_output( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.InputModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.InputModel, _types.InputModel, IO[bytes]], **kwargs: Any ) -> None: """Expected body parameter: @@ -194,10 +210,11 @@ def input_to_input_output( # pylint: disable=inconsistent-return-statements { "name": "Madge" - }. + } - :param body: Is one of the following types: InputModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.usage.models.InputModel or JSON or IO[bytes] + :param body: Is either a InputModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.usage.models.InputModel or + ~specs.azure.clientgenerator.core.usage.types.InputModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -256,7 +273,7 @@ def output_to_input_output(self, **kwargs: Any) -> _models.OutputModel: { "name": "Madge" - }. + } :return: OutputModel. The OutputModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.usage.models.OutputModel @@ -332,7 +349,7 @@ def model_in_read_only_property( "result": { "name": "Madge" } - }. + } :param body: Required. :type body: ~specs.azure.clientgenerator.core.usage.models.RoundTripModel @@ -346,7 +363,7 @@ def model_in_read_only_property( @overload def model_in_read_only_property( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.RoundTripModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.RoundTripModel: """ "ResultModel" should be usage=output, as it is read-only and does not exist in request body. @@ -365,10 +382,10 @@ def model_in_read_only_property( "result": { "name": "Madge" } - }. + } :param body: Required. - :type body: JSON + :type body: ~specs.azure.clientgenerator.core.usage.types.RoundTripModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -398,7 +415,7 @@ def model_in_read_only_property( "result": { "name": "Madge" } - }. + } :param body: Required. :type body: IO[bytes] @@ -412,7 +429,7 @@ def model_in_read_only_property( @distributed_trace def model_in_read_only_property( - self, body: Union[_models.RoundTripModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.RoundTripModel, _types.RoundTripModel, IO[bytes]], **kwargs: Any ) -> _models.RoundTripModel: """ "ResultModel" should be usage=output, as it is read-only and does not exist in request body. @@ -431,10 +448,11 @@ def model_in_read_only_property( "result": { "name": "Madge" } - }. + } - :param body: Is one of the following types: RoundTripModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.clientgenerator.core.usage.models.RoundTripModel or JSON or IO[bytes] + :param body: Is either a RoundTripModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.clientgenerator.core.usage.models.RoundTripModel or + ~specs.azure.clientgenerator.core.usage.types.RoundTripModel or IO[bytes] :return: RoundTripModel. The RoundTripModel is compatible with MutableMapping :rtype: ~specs.azure.clientgenerator.core.usage.models.RoundTripModel :raises ~azure.core.exceptions.HttpResponseError: @@ -511,7 +529,7 @@ def orphan_model_serializable( # pylint: disable=inconsistent-return-statements { "name": "name", "desc": "desc" - }. + } :param body: Required. :type body: any @@ -559,3 +577,82 @@ def orphan_model_serializable( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) # type: ignore + + +class NamespaceUsageOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~specs.azure.clientgenerator.core.usage.UsageClient`'s + :attr:`namespace_usage` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: UsageClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def namespace_model_serializable( # pylint: disable=inconsistent-return-statements + self, body: Any, **kwargs: Any + ) -> None: + """Serialize the 'NamespaceModel' as request body. + + Expected body parameter: + + .. code-block:: json + + { + "name": "test" + } + + :param body: Required. + :type body: any + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_namespace_usage_namespace_model_serializable_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/types.py index fe0b2d04ccf2..e0a67a3bcf5e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-usage/specs/azure/clientgenerator/core/usage/types.py @@ -20,6 +20,28 @@ class InputModel(TypedDict, total=False): """Required.""" +class NamespaceModel(TypedDict, total=False): + """NamespaceModel. + + :ivar name: Required. + :vartype name: str + """ + + name: Required[str] + """Required.""" + + +class NestedNamespaceModel(TypedDict, total=False): + """NestedNamespaceModel. + + :ivar value: Required. + :vartype value: str + """ + + value: Required[str] + """Required.""" + + class OrphanModel(TypedDict, total=False): """Not used anywhere, but access is override to public so still need to be generated and exported with serialization. @@ -62,7 +84,7 @@ class RoundTripModel(TypedDict, total=False): """RoundTripModel. :ivar result: Required. - :vartype result: ~specs.azure.clientgenerator.core.usage.models.ResultModel + :vartype result: "ResultModel" """ result: Required["ResultModel"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/pyproject.toml index 1a5a30200ef9..118fd6491b54 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_operations/_operations.py index 6f30d678fe22..88abd30ead4f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_operations/_operations.py @@ -28,13 +28,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import BasicClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] List = list @@ -251,7 +250,7 @@ def create_or_update( @overload def create_or_update( - self, id: int, resource: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, id: int, resource: _types.User, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.User: """Adds a user or updates a user's fields. @@ -260,7 +259,7 @@ def create_or_update( :param id: The user's id. Required. :type id: int :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~specs.azure.core.basic.types.User :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -290,16 +289,18 @@ def create_or_update( """ @distributed_trace - def create_or_update(self, id: int, resource: Union[_models.User, JSON, IO[bytes]], **kwargs: Any) -> _models.User: + def create_or_update( + self, id: int, resource: Union[_models.User, _types.User, IO[bytes]], **kwargs: Any + ) -> _models.User: """Adds a user or updates a user's fields. Creates or updates a User. :param id: The user's id. Required. :type id: int - :param resource: The resource instance. Is one of the following types: User, JSON, IO[bytes] - Required. - :type resource: ~specs.azure.core.basic.models.User or JSON or IO[bytes] + :param resource: The resource instance. Is either a User type or a IO[bytes] type. Required. + :type resource: ~specs.azure.core.basic.models.User or ~specs.azure.core.basic.types.User or + IO[bytes] :return: User. The User is compatible with MutableMapping :rtype: ~specs.azure.core.basic.models.User :raises ~azure.core.exceptions.HttpResponseError: @@ -387,7 +388,7 @@ def create_or_replace( @overload def create_or_replace( - self, id: int, resource: JSON, *, content_type: str = "application/json", **kwargs: Any + self, id: int, resource: _types.User, *, content_type: str = "application/json", **kwargs: Any ) -> _models.User: """Adds a user or replaces a user's fields. @@ -396,7 +397,7 @@ def create_or_replace( :param id: The user's id. Required. :type id: int :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~specs.azure.core.basic.types.User :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -426,16 +427,18 @@ def create_or_replace( """ @distributed_trace - def create_or_replace(self, id: int, resource: Union[_models.User, JSON, IO[bytes]], **kwargs: Any) -> _models.User: + def create_or_replace( + self, id: int, resource: Union[_models.User, _types.User, IO[bytes]], **kwargs: Any + ) -> _models.User: """Adds a user or replaces a user's fields. Creates or replaces a User. :param id: The user's id. Required. :type id: int - :param resource: The resource instance. Is one of the following types: User, JSON, IO[bytes] - Required. - :type resource: ~specs.azure.core.basic.models.User or JSON or IO[bytes] + :param resource: The resource instance. Is either a User type or a IO[bytes] type. Required. + :type resource: ~specs.azure.core.basic.models.User or ~specs.azure.core.basic.types.User or + IO[bytes] :return: User. The User is compatible with MutableMapping :rtype: ~specs.azure.core.basic.models.User :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_operations/_operations.py index eb81e1b004ad..58de5be8cbf5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_operations/_operations.py @@ -30,7 +30,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_basic_create_or_replace_request, build_basic_create_or_update_request, @@ -44,7 +44,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import BasicClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] List = list @@ -76,7 +75,7 @@ async def create_or_update( @overload async def create_or_update( - self, id: int, resource: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, id: int, resource: _types.User, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.User: """Adds a user or updates a user's fields. @@ -85,7 +84,7 @@ async def create_or_update( :param id: The user's id. Required. :type id: int :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~specs.azure.core.basic.types.User :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -116,7 +115,7 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, id: int, resource: Union[_models.User, JSON, IO[bytes]], **kwargs: Any + self, id: int, resource: Union[_models.User, _types.User, IO[bytes]], **kwargs: Any ) -> _models.User: """Adds a user or updates a user's fields. @@ -124,9 +123,9 @@ async def create_or_update( :param id: The user's id. Required. :type id: int - :param resource: The resource instance. Is one of the following types: User, JSON, IO[bytes] - Required. - :type resource: ~specs.azure.core.basic.models.User or JSON or IO[bytes] + :param resource: The resource instance. Is either a User type or a IO[bytes] type. Required. + :type resource: ~specs.azure.core.basic.models.User or ~specs.azure.core.basic.types.User or + IO[bytes] :return: User. The User is compatible with MutableMapping :rtype: ~specs.azure.core.basic.models.User :raises ~azure.core.exceptions.HttpResponseError: @@ -214,7 +213,7 @@ async def create_or_replace( @overload async def create_or_replace( - self, id: int, resource: JSON, *, content_type: str = "application/json", **kwargs: Any + self, id: int, resource: _types.User, *, content_type: str = "application/json", **kwargs: Any ) -> _models.User: """Adds a user or replaces a user's fields. @@ -223,7 +222,7 @@ async def create_or_replace( :param id: The user's id. Required. :type id: int :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~specs.azure.core.basic.types.User :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -254,7 +253,7 @@ async def create_or_replace( @distributed_trace_async async def create_or_replace( - self, id: int, resource: Union[_models.User, JSON, IO[bytes]], **kwargs: Any + self, id: int, resource: Union[_models.User, _types.User, IO[bytes]], **kwargs: Any ) -> _models.User: """Adds a user or replaces a user's fields. @@ -262,9 +261,9 @@ async def create_or_replace( :param id: The user's id. Required. :type id: int - :param resource: The resource instance. Is one of the following types: User, JSON, IO[bytes] - Required. - :type resource: ~specs.azure.core.basic.models.User or JSON or IO[bytes] + :param resource: The resource instance. Is either a User type or a IO[bytes] type. Required. + :type resource: ~specs.azure.core.basic.models.User or ~specs.azure.core.basic.types.User or + IO[bytes] :return: User. The User is compatible with MutableMapping :rtype: ~specs.azure.core.basic.models.User :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/types.py index 03c07f602247..800050fd9bb3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-basic/specs/azure/core/basic/types.py @@ -17,7 +17,7 @@ class User(TypedDict, total=False): :ivar name: The user's name. Required. :vartype name: str :ivar orders: The user's order list. - :vartype orders: list[~specs.azure.core.basic.models.UserOrder] + :vartype orders: list["UserOrder"] :ivar etag: The entity tag for this resource. Required. :vartype etag: str """ @@ -32,17 +32,6 @@ class User(TypedDict, total=False): """The entity tag for this resource. Required.""" -class UserList(TypedDict, total=False): - """UserList. - - :ivar users: Required. - :vartype users: list[~specs.azure.core.basic.models.User] - """ - - users: Required[list["User"]] - """Required.""" - - class UserOrder(TypedDict, total=False): """UserOrder for testing list with expand. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/pyproject.toml index 6509f7ea17b4..0bd8571054e9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_operations/_operations.py index 57b95b5484f5..4f2d1d58ddf4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_operations/_operations.py @@ -28,13 +28,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import RpcClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -67,7 +66,7 @@ def build_rpc_long_running_rpc_request(**kwargs: Any) -> HttpRequest: class _RpcClientOperationsMixin(ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], RpcClientConfiguration]): def _long_running_rpc_initial( - self, body: Union[_models.GenerationOptions, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.GenerationOptions, _types.GenerationOptions, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -149,14 +148,14 @@ def begin_long_running_rpc( @overload def begin_long_running_rpc( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.GenerationOptions, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.GenerationResult]: """Generate data. Generate data. :param body: The body parameter. Required. - :type body: JSON + :type body: ~specs.azure.core.lro.rpc.types.GenerationOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -187,15 +186,16 @@ def begin_long_running_rpc( @distributed_trace def begin_long_running_rpc( - self, body: Union[_models.GenerationOptions, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.GenerationOptions, _types.GenerationOptions, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.GenerationResult]: """Generate data. Generate data. - :param body: The body parameter. Is one of the following types: GenerationOptions, JSON, - IO[bytes] Required. - :type body: ~specs.azure.core.lro.rpc.models.GenerationOptions or JSON or IO[bytes] + :param body: The body parameter. Is either a GenerationOptions type or a IO[bytes] type. + Required. + :type body: ~specs.azure.core.lro.rpc.models.GenerationOptions or + ~specs.azure.core.lro.rpc.types.GenerationOptions or IO[bytes] :return: An instance of LROPoller that returns GenerationResult. The GenerationResult is compatible with MutableMapping :rtype: ~azure.core.polling.LROPoller[~specs.azure.core.lro.rpc.models.GenerationResult] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_operations/_operations.py index 9b675f95246c..2822a1cd7991 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_operations/_operations.py @@ -29,13 +29,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_rpc_long_running_rpc_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import RpcClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -45,7 +44,7 @@ class _RpcClientOperationsMixin( ): async def _long_running_rpc_initial( - self, body: Union[_models.GenerationOptions, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.GenerationOptions, _types.GenerationOptions, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -127,14 +126,14 @@ async def begin_long_running_rpc( @overload async def begin_long_running_rpc( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.GenerationOptions, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.GenerationResult]: """Generate data. Generate data. :param body: The body parameter. Required. - :type body: JSON + :type body: ~specs.azure.core.lro.rpc.types.GenerationOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -165,15 +164,16 @@ async def begin_long_running_rpc( @distributed_trace_async async def begin_long_running_rpc( - self, body: Union[_models.GenerationOptions, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.GenerationOptions, _types.GenerationOptions, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.GenerationResult]: """Generate data. Generate data. - :param body: The body parameter. Is one of the following types: GenerationOptions, JSON, - IO[bytes] Required. - :type body: ~specs.azure.core.lro.rpc.models.GenerationOptions or JSON or IO[bytes] + :param body: The body parameter. Is either a GenerationOptions type or a IO[bytes] type. + Required. + :type body: ~specs.azure.core.lro.rpc.models.GenerationOptions or + ~specs.azure.core.lro.rpc.types.GenerationOptions or IO[bytes] :return: An instance of AsyncLROPoller that returns GenerationResult. The GenerationResult is compatible with MutableMapping :rtype: ~azure.core.polling.AsyncLROPoller[~specs.azure.core.lro.rpc.models.GenerationResult] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/types.py index 9b3bc6f4e284..d4103fdfd8aa 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-rpc/specs/azure/core/lro/rpc/types.py @@ -18,14 +18,3 @@ class GenerationOptions(TypedDict, total=False): prompt: Required[str] """Prompt. Required.""" - - -class GenerationResult(TypedDict, total=False): - """Result of the generation. - - :ivar data: The data. Required. - :vartype data: str - """ - - data: Required[str] - """The data. Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/pyproject.toml index d162f8adaeed..ecddb7a35b3b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_operations/_operations.py index 8ed771bc555b..d69e957e4b86 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_operations/_operations.py @@ -28,13 +28,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import StandardClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -123,7 +122,7 @@ class _StandardClientOperationsMixin( ): def _create_or_replace_initial( - self, name: str, resource: Union[_models.User, JSON, IO[bytes]], **kwargs: Any + self, name: str, resource: Union[_models.User, _types.User, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -207,7 +206,7 @@ def begin_create_or_replace( @overload def begin_create_or_replace( - self, name: str, resource: JSON, *, content_type: str = "application/json", **kwargs: Any + self, name: str, resource: _types.User, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.User]: """Adds a user or replaces a user's fields. @@ -216,7 +215,7 @@ def begin_create_or_replace( :param name: The name of user. Required. :type name: str :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~specs.azure.core.lro.standard.types.User :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -247,7 +246,7 @@ def begin_create_or_replace( @distributed_trace def begin_create_or_replace( - self, name: str, resource: Union[_models.User, JSON, IO[bytes]], **kwargs: Any + self, name: str, resource: Union[_models.User, _types.User, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.User]: """Adds a user or replaces a user's fields. @@ -255,9 +254,9 @@ def begin_create_or_replace( :param name: The name of user. Required. :type name: str - :param resource: The resource instance. Is one of the following types: User, JSON, IO[bytes] - Required. - :type resource: ~specs.azure.core.lro.standard.models.User or JSON or IO[bytes] + :param resource: The resource instance. Is either a User type or a IO[bytes] type. Required. + :type resource: ~specs.azure.core.lro.standard.models.User or + ~specs.azure.core.lro.standard.types.User or IO[bytes] :return: An instance of LROPoller that returns User. The User is compatible with MutableMapping :rtype: ~azure.core.polling.LROPoller[~specs.azure.core.lro.standard.models.User] :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_operations/_operations.py index 47a421f4df19..c100f2664774 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_operations/_operations.py @@ -29,7 +29,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_standard_create_or_replace_request, build_standard_delete_request, @@ -39,7 +39,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import StandardClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -49,7 +48,7 @@ class _StandardClientOperationsMixin( ): async def _create_or_replace_initial( - self, name: str, resource: Union[_models.User, JSON, IO[bytes]], **kwargs: Any + self, name: str, resource: Union[_models.User, _types.User, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -134,7 +133,7 @@ async def begin_create_or_replace( @overload async def begin_create_or_replace( - self, name: str, resource: JSON, *, content_type: str = "application/json", **kwargs: Any + self, name: str, resource: _types.User, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.User]: """Adds a user or replaces a user's fields. @@ -143,7 +142,7 @@ async def begin_create_or_replace( :param name: The name of user. Required. :type name: str :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~specs.azure.core.lro.standard.types.User :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -176,7 +175,7 @@ async def begin_create_or_replace( @distributed_trace_async async def begin_create_or_replace( - self, name: str, resource: Union[_models.User, JSON, IO[bytes]], **kwargs: Any + self, name: str, resource: Union[_models.User, _types.User, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.User]: """Adds a user or replaces a user's fields. @@ -184,9 +183,9 @@ async def begin_create_or_replace( :param name: The name of user. Required. :type name: str - :param resource: The resource instance. Is one of the following types: User, JSON, IO[bytes] - Required. - :type resource: ~specs.azure.core.lro.standard.models.User or JSON or IO[bytes] + :param resource: The resource instance. Is either a User type or a IO[bytes] type. Required. + :type resource: ~specs.azure.core.lro.standard.models.User or + ~specs.azure.core.lro.standard.types.User or IO[bytes] :return: An instance of AsyncLROPoller that returns User. The User is compatible with MutableMapping :rtype: ~azure.core.polling.AsyncLROPoller[~specs.azure.core.lro.standard.models.User] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/types.py index a0844fed0b43..fabef8da10d4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-lro-standard/specs/azure/core/lro/standard/types.py @@ -9,21 +9,6 @@ from typing_extensions import Required, TypedDict -class ExportedUser(TypedDict, total=False): - """The exported user data. - - :ivar name: The name of user. Required. - :vartype name: str - :ivar resource_uri: The exported URI. Required. - :vartype resource_uri: str - """ - - name: Required[str] - """The name of user. Required.""" - resourceUri: Required[str] - """The exported URI. Required.""" - - class User(TypedDict, total=False): """Details about a user. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/pyproject.toml index a95003594934..881f348cd9da 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/operations/_operations.py index b051970ec2c5..2cc2e8a5d384 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/operations/_operations.py @@ -26,7 +26,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -36,7 +36,6 @@ ) from .._configuration import ModelClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -217,12 +216,12 @@ async def post( @overload async def post( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.AzureEmbeddingModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AzureEmbeddingModel: """post a model which has an embeddingVector property. :param body: _. Required. - :type body: JSON + :type body: ~specs.azure.core.model.types.AzureEmbeddingModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -249,12 +248,13 @@ async def post( @distributed_trace_async async def post( - self, body: Union[_models.AzureEmbeddingModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.AzureEmbeddingModel, _types.AzureEmbeddingModel, IO[bytes]], **kwargs: Any ) -> _models.AzureEmbeddingModel: """post a model which has an embeddingVector property. - :param body: _. Is one of the following types: AzureEmbeddingModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.core.model.models.AzureEmbeddingModel or JSON or IO[bytes] + :param body: _. Is either a AzureEmbeddingModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.core.model.models.AzureEmbeddingModel or + ~specs.azure.core.model.types.AzureEmbeddingModel or IO[bytes] :return: AzureEmbeddingModel. The AzureEmbeddingModel is compatible with MutableMapping :rtype: ~specs.azure.core.model.models.AzureEmbeddingModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/operations/_operations.py index 5f2e5709a79a..bf925808d059 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import ModelClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -261,11 +260,13 @@ def post( """ @overload - def post(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.AzureEmbeddingModel: + def post( + self, body: _types.AzureEmbeddingModel, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AzureEmbeddingModel: """post a model which has an embeddingVector property. :param body: _. Required. - :type body: JSON + :type body: ~specs.azure.core.model.types.AzureEmbeddingModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -292,12 +293,13 @@ def post( @distributed_trace def post( - self, body: Union[_models.AzureEmbeddingModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.AzureEmbeddingModel, _types.AzureEmbeddingModel, IO[bytes]], **kwargs: Any ) -> _models.AzureEmbeddingModel: """post a model which has an embeddingVector property. - :param body: _. Is one of the following types: AzureEmbeddingModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.core.model.models.AzureEmbeddingModel or JSON or IO[bytes] + :param body: _. Is either a AzureEmbeddingModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.core.model.models.AzureEmbeddingModel or + ~specs.azure.core.model.types.AzureEmbeddingModel or IO[bytes] :return: AzureEmbeddingModel. The AzureEmbeddingModel is compatible with MutableMapping :rtype: ~specs.azure.core.model.models.AzureEmbeddingModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-model/specs/azure/core/model/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/pyproject.toml index 4bb188a86514..99dcb317c2eb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/operations/_operations.py index 82f8c6301b12..fec798a69b0c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ..._utils.utils import ClientMixinABC @@ -44,7 +44,6 @@ T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] class TwoModelsAsPageItemOperations: @@ -362,7 +361,7 @@ def list_with_parameters( @overload def list_with_parameters( self, - body_input: JSON, + body_input: _types.ListItemInputBody, *, another: Optional[Union[str, _models.ListItemInputExtensibleEnum]] = None, content_type: str = "application/json", @@ -371,7 +370,7 @@ def list_with_parameters( """List with extensible enum parameter Azure.Core.Page<>. :param body_input: The body of the input. Required. - :type body_input: JSON + :type body_input: ~specs.azure.core.page.types.ListItemInputBody :keyword another: Another query parameter. Known values are: "First" and "Second". Default value is None. :paramtype another: str or ~specs.azure.core.page.models.ListItemInputExtensibleEnum @@ -410,16 +409,17 @@ def list_with_parameters( @distributed_trace def list_with_parameters( self, - body_input: Union[_models.ListItemInputBody, JSON, IO[bytes]], + body_input: Union[_models.ListItemInputBody, _types.ListItemInputBody, IO[bytes]], *, another: Optional[Union[str, _models.ListItemInputExtensibleEnum]] = None, **kwargs: Any ) -> AsyncItemPaged["_models.User"]: """List with extensible enum parameter Azure.Core.Page<>. - :param body_input: The body of the input. Is one of the following types: ListItemInputBody, - JSON, IO[bytes] Required. - :type body_input: ~specs.azure.core.page.models.ListItemInputBody or JSON or IO[bytes] + :param body_input: The body of the input. Is either a ListItemInputBody type or a IO[bytes] + type. Required. + :type body_input: ~specs.azure.core.page.models.ListItemInputBody or + ~specs.azure.core.page.types.ListItemInputBody or IO[bytes] :keyword another: Another query parameter. Known values are: "First" and "Second". Default value is None. :paramtype another: str or ~specs.azure.core.page.models.ListItemInputExtensibleEnum diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/operations/_operations.py index 4d8f44f4ae40..814f8b78ffcf 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/operations/_operations.py @@ -26,7 +26,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import PageClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer @@ -34,7 +34,6 @@ T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -495,7 +494,7 @@ def list_with_parameters( @overload def list_with_parameters( self, - body_input: JSON, + body_input: _types.ListItemInputBody, *, another: Optional[Union[str, _models.ListItemInputExtensibleEnum]] = None, content_type: str = "application/json", @@ -504,7 +503,7 @@ def list_with_parameters( """List with extensible enum parameter Azure.Core.Page<>. :param body_input: The body of the input. Required. - :type body_input: JSON + :type body_input: ~specs.azure.core.page.types.ListItemInputBody :keyword another: Another query parameter. Known values are: "First" and "Second". Default value is None. :paramtype another: str or ~specs.azure.core.page.models.ListItemInputExtensibleEnum @@ -543,16 +542,17 @@ def list_with_parameters( @distributed_trace def list_with_parameters( self, - body_input: Union[_models.ListItemInputBody, JSON, IO[bytes]], + body_input: Union[_models.ListItemInputBody, _types.ListItemInputBody, IO[bytes]], *, another: Optional[Union[str, _models.ListItemInputExtensibleEnum]] = None, **kwargs: Any, ) -> ItemPaged["_models.User"]: """List with extensible enum parameter Azure.Core.Page<>. - :param body_input: The body of the input. Is one of the following types: ListItemInputBody, - JSON, IO[bytes] Required. - :type body_input: ~specs.azure.core.page.models.ListItemInputBody or JSON or IO[bytes] + :param body_input: The body of the input. Is either a ListItemInputBody type or a IO[bytes] + type. Required. + :type body_input: ~specs.azure.core.page.models.ListItemInputBody or + ~specs.azure.core.page.types.ListItemInputBody or IO[bytes] :keyword another: Another query parameter. Known values are: "First" and "Second". Default value is None. :paramtype another: str or ~specs.azure.core.page.models.ListItemInputExtensibleEnum diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/types.py index 7091cc237d43..f6015f524854 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-page/specs/azure/core/page/types.py @@ -9,17 +9,6 @@ from typing_extensions import Required, TypedDict -class FirstItem(TypedDict, total=False): - """First item. - - :ivar id: The id of the item. Required. - :vartype id: int - """ - - id: Required[int] - """The id of the item. Required.""" - - class ListItemInputBody(TypedDict, total=False): """The body of the input. @@ -29,56 +18,3 @@ class ListItemInputBody(TypedDict, total=False): inputName: Required[str] """The name of the input. Required.""" - - -class SecondItem(TypedDict, total=False): - """Second item. - - :ivar name: The name of the item. Required. - :vartype name: str - """ - - name: Required[str] - """The name of the item. Required.""" - - -class User(TypedDict, total=False): - """Details about a user. - - :ivar id: The user's id. Required. - :vartype id: int - :ivar name: The user's name. Required. - :vartype name: str - :ivar orders: The user's order list. - :vartype orders: list[~specs.azure.core.page.models.UserOrder] - :ivar etag: The entity tag for this resource. Required. - :vartype etag: str - """ - - id: Required[int] - """The user's id. Required.""" - name: Required[str] - """The user's name. Required.""" - orders: list["UserOrder"] - """The user's order list.""" - etag: Required[str] - """The entity tag for this resource. Required.""" - - -class UserOrder(TypedDict, total=False): - """UserOrder for testing list with expand. - - :ivar id: The user's id. Required. - :vartype id: int - :ivar user_id: The user's id. Required. - :vartype user_id: int - :ivar detail: The user's order detail. Required. - :vartype detail: str - """ - - id: Required[int] - """The user's id. Required.""" - userId: Required[int] - """The user's id. Required.""" - detail: Required[str] - """The user's order detail. Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/pyproject.toml index 341e0f56baa7..6009d0f554b5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/operations/_operations.py index e152dcd27dca..81ab9712b9dd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/operations/_operations.py @@ -26,7 +26,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -38,7 +38,6 @@ ) from .._configuration import ScalarClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -189,12 +188,12 @@ async def post( @overload async def post( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.AzureLocationModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AzureLocationModel: """post a model which has azureLocation property. :param body: _. Required. - :type body: JSON + :type body: ~specs.azure.core.scalar.types.AzureLocationModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -221,12 +220,13 @@ async def post( @distributed_trace_async async def post( - self, body: Union[_models.AzureLocationModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.AzureLocationModel, _types.AzureLocationModel, IO[bytes]], **kwargs: Any ) -> _models.AzureLocationModel: """post a model which has azureLocation property. - :param body: _. Is one of the following types: AzureLocationModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.core.scalar.models.AzureLocationModel or JSON or IO[bytes] + :param body: _. Is either a AzureLocationModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.core.scalar.models.AzureLocationModel or + ~specs.azure.core.scalar.types.AzureLocationModel or IO[bytes] :return: AzureLocationModel. The AzureLocationModel is compatible with MutableMapping :rtype: ~specs.azure.core.scalar.models.AzureLocationModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/operations/_operations.py index 924841c158f6..24a7d190cf06 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import ScalarClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -256,11 +255,13 @@ def post( """ @overload - def post(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.AzureLocationModel: + def post( + self, body: _types.AzureLocationModel, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AzureLocationModel: """post a model which has azureLocation property. :param body: _. Required. - :type body: JSON + :type body: ~specs.azure.core.scalar.types.AzureLocationModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -287,12 +288,13 @@ def post( @distributed_trace def post( - self, body: Union[_models.AzureLocationModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.AzureLocationModel, _types.AzureLocationModel, IO[bytes]], **kwargs: Any ) -> _models.AzureLocationModel: """post a model which has azureLocation property. - :param body: _. Is one of the following types: AzureLocationModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.core.scalar.models.AzureLocationModel or JSON or IO[bytes] + :param body: _. Is either a AzureLocationModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.core.scalar.models.AzureLocationModel or + ~specs.azure.core.scalar.types.AzureLocationModel or IO[bytes] :return: AzureLocationModel. The AzureLocationModel is compatible with MutableMapping :rtype: ~specs.azure.core.scalar.models.AzureLocationModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-scalar/specs/azure/core/scalar/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/pyproject.toml index 8459f6274776..1fe699194eef 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_operations/_operations.py index 4a9838dcbc30..f313e8c56cb4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_operations/_operations.py @@ -29,13 +29,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import TraitsClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC, prep_if_match, prep_if_none_match -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -246,14 +245,14 @@ def repeatable_action( @overload def repeatable_action( - self, id: int, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, id: int, body: _types.UserActionParam, *, content_type: str = "application/json", **kwargs: Any ) -> _models.UserActionResponse: """Test for repeatable requests. :param id: The user's id. Required. :type id: int :param body: The body parameter. Required. - :type body: JSON + :type body: ~specs.azure.core.traits.types.UserActionParam :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -282,15 +281,16 @@ def repeatable_action( @distributed_trace def repeatable_action( - self, id: int, body: Union[_models.UserActionParam, JSON, IO[bytes]], **kwargs: Any + self, id: int, body: Union[_models.UserActionParam, _types.UserActionParam, IO[bytes]], **kwargs: Any ) -> _models.UserActionResponse: """Test for repeatable requests. :param id: The user's id. Required. :type id: int - :param body: The body parameter. Is one of the following types: UserActionParam, JSON, - IO[bytes] Required. - :type body: ~specs.azure.core.traits.models.UserActionParam or JSON or IO[bytes] + :param body: The body parameter. Is either a UserActionParam type or a IO[bytes] type. + Required. + :type body: ~specs.azure.core.traits.models.UserActionParam or + ~specs.azure.core.traits.types.UserActionParam or IO[bytes] :return: UserActionResponse. The UserActionResponse is compatible with MutableMapping :rtype: ~specs.azure.core.traits.models.UserActionResponse :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_operations/_operations.py index 9cfb460c8201..a036785d6afd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_operations/_operations.py @@ -29,13 +29,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_traits_repeatable_action_request, build_traits_smoke_test_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import TraitsClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -166,14 +165,14 @@ async def repeatable_action( @overload async def repeatable_action( - self, id: int, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, id: int, body: _types.UserActionParam, *, content_type: str = "application/json", **kwargs: Any ) -> _models.UserActionResponse: """Test for repeatable requests. :param id: The user's id. Required. :type id: int :param body: The body parameter. Required. - :type body: JSON + :type body: ~specs.azure.core.traits.types.UserActionParam :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -202,15 +201,16 @@ async def repeatable_action( @distributed_trace_async async def repeatable_action( - self, id: int, body: Union[_models.UserActionParam, JSON, IO[bytes]], **kwargs: Any + self, id: int, body: Union[_models.UserActionParam, _types.UserActionParam, IO[bytes]], **kwargs: Any ) -> _models.UserActionResponse: """Test for repeatable requests. :param id: The user's id. Required. :type id: int - :param body: The body parameter. Is one of the following types: UserActionParam, JSON, - IO[bytes] Required. - :type body: ~specs.azure.core.traits.models.UserActionParam or JSON or IO[bytes] + :param body: The body parameter. Is either a UserActionParam type or a IO[bytes] type. + Required. + :type body: ~specs.azure.core.traits.models.UserActionParam or + ~specs.azure.core.traits.types.UserActionParam or IO[bytes] :return: UserActionResponse. The UserActionResponse is compatible with MutableMapping :rtype: ~specs.azure.core.traits.models.UserActionResponse :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/types.py index 321efad9915b..e8a00e58e0c2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-core-traits/specs/azure/core/traits/types.py @@ -9,21 +9,6 @@ from typing_extensions import Required, TypedDict -class User(TypedDict, total=False): - """Sample Model. - - :ivar id: The user's id. Required. - :vartype id: int - :ivar name: The user's name. - :vartype name: str - """ - - id: Required[int] - """The user's id. Required.""" - name: str - """The user's name.""" - - class UserActionParam(TypedDict, total=False): """User action param. @@ -33,14 +18,3 @@ class UserActionParam(TypedDict, total=False): userActionValue: Required[str] """User action value. Required.""" - - -class UserActionResponse(TypedDict, total=False): - """User action response. - - :ivar user_action_result: User action result. Required. - :vartype user_action_result: str - """ - - userActionResult: Required[str] - """User action result. Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/pyproject.toml index c316bf2202d2..2b4b1496b119 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_operations/_operations.py index 7a874fea5b28..502576b69507 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_operations/_operations.py @@ -24,13 +24,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import DurationClientConfiguration from .._utils.model_base import SdkJSONEncoder from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -73,11 +72,13 @@ def duration_constant( """ @overload - def duration_constant(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def duration_constant( + self, body: _types.DurationModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Test duration with azure specific encoding. :param body: Required. - :type body: JSON + :type body: ~specs.azure.encode.duration.types.DurationModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -102,12 +103,13 @@ def duration_constant(self, body: IO[bytes], *, content_type: str = "application @distributed_trace def duration_constant( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationModel, _types.DurationModel, IO[bytes]], **kwargs: Any ) -> None: """Test duration with azure specific encoding. - :param body: Is one of the following types: DurationModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.encode.duration.models.DurationModel or JSON or IO[bytes] + :param body: Is either a DurationModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.encode.duration.models.DurationModel or + ~specs.azure.encode.duration.types.DurationModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_operations/_operations.py index 5734ed676638..3efdac4a6e21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_operations/_operations.py @@ -25,13 +25,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_duration_duration_constant_request from ..._utils.model_base import SdkJSONEncoder from ..._utils.utils import ClientMixinABC from .._configuration import DurationClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -57,11 +56,13 @@ async def duration_constant( """ @overload - async def duration_constant(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def duration_constant( + self, body: _types.DurationModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Test duration with azure specific encoding. :param body: Required. - :type body: JSON + :type body: ~specs.azure.encode.duration.types.DurationModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -87,11 +88,14 @@ async def duration_constant( """ @distributed_trace_async - async def duration_constant(self, body: Union[_models.DurationModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def duration_constant( + self, body: Union[_models.DurationModel, _types.DurationModel, IO[bytes]], **kwargs: Any + ) -> None: """Test duration with azure specific encoding. - :param body: Is one of the following types: DurationModel, JSON, IO[bytes] Required. - :type body: ~specs.azure.encode.duration.models.DurationModel or JSON or IO[bytes] + :param body: Is either a DurationModel type or a IO[bytes] type. Required. + :type body: ~specs.azure.encode.duration.models.DurationModel or + ~specs.azure.encode.duration.types.DurationModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-encode-duration/specs/azure/encode/duration/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/pyproject.toml index f970b4382007..d56f7c69afc7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_operations/_operations.py index ad9ed44fe07d..fe596ff91e93 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import AzureExampleClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -96,12 +95,18 @@ def basic_action( @overload def basic_action( - self, body: JSON, *, query_param: str, header_param: str, content_type: str = "application/json", **kwargs: Any + self, + body: _types.ActionRequest, + *, + query_param: str, + header_param: str, + content_type: str = "application/json", + **kwargs: Any ) -> _models.ActionResponse: """basic_action. :param body: Required. - :type body: JSON + :type body: ~specs.azure.example.basic.types.ActionRequest :keyword query_param: Required. :paramtype query_param: str :keyword header_param: Required. @@ -142,12 +147,18 @@ def basic_action( @distributed_trace def basic_action( - self, body: Union[_models.ActionRequest, JSON, IO[bytes]], *, query_param: str, header_param: str, **kwargs: Any + self, + body: Union[_models.ActionRequest, _types.ActionRequest, IO[bytes]], + *, + query_param: str, + header_param: str, + **kwargs: Any ) -> _models.ActionResponse: """basic_action. - :param body: Is one of the following types: ActionRequest, JSON, IO[bytes] Required. - :type body: ~specs.azure.example.basic.models.ActionRequest or JSON or IO[bytes] + :param body: Is either a ActionRequest type or a IO[bytes] type. Required. + :type body: ~specs.azure.example.basic.models.ActionRequest or + ~specs.azure.example.basic.types.ActionRequest or IO[bytes] :keyword query_param: Required. :paramtype query_param: str :keyword header_param: Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_operations/_operations.py index 3f83b2d50cd1..40bb92b6aef5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_operations/_operations.py @@ -27,13 +27,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_azure_example_basic_action_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import AzureExampleClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -70,12 +69,18 @@ async def basic_action( @overload async def basic_action( - self, body: JSON, *, query_param: str, header_param: str, content_type: str = "application/json", **kwargs: Any + self, + body: _types.ActionRequest, + *, + query_param: str, + header_param: str, + content_type: str = "application/json", + **kwargs: Any ) -> _models.ActionResponse: """basic_action. :param body: Required. - :type body: JSON + :type body: ~specs.azure.example.basic.types.ActionRequest :keyword query_param: Required. :paramtype query_param: str :keyword header_param: Required. @@ -116,12 +121,18 @@ async def basic_action( @distributed_trace_async async def basic_action( - self, body: Union[_models.ActionRequest, JSON, IO[bytes]], *, query_param: str, header_param: str, **kwargs: Any + self, + body: Union[_models.ActionRequest, _types.ActionRequest, IO[bytes]], + *, + query_param: str, + header_param: str, + **kwargs: Any ) -> _models.ActionResponse: """basic_action. - :param body: Is one of the following types: ActionRequest, JSON, IO[bytes] Required. - :type body: ~specs.azure.example.basic.models.ActionRequest or JSON or IO[bytes] + :param body: Is either a ActionRequest type or a IO[bytes] type. Required. + :type body: ~specs.azure.example.basic.models.ActionRequest or + ~specs.azure.example.basic.types.ActionRequest or IO[bytes] :keyword query_param: Required. :paramtype query_param: str :keyword header_param: Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/types.py index a0098bcf0e1c..4a6f425a2a94 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-example-basic/specs/azure/example/basic/types.py @@ -19,27 +19,7 @@ class ActionRequest(TypedDict, total=False): :ivar string_property: Required. :vartype string_property: str :ivar model_property: - :vartype model_property: ~specs.azure.example.basic.models.Model - :ivar array_property: - :vartype array_property: list[str] - :ivar record_property: - :vartype record_property: dict[str, str] - """ - - stringProperty: Required[str] - """Required.""" - modelProperty: "Model" - arrayProperty: list[str] - recordProperty: dict[str, str] - - -class ActionResponse(TypedDict, total=False): - """ActionResponse. - - :ivar string_property: Required. - :vartype string_property: str - :ivar model_property: - :vartype model_property: ~specs.azure.example.basic.models.Model + :vartype model_property: "Model" :ivar array_property: :vartype array_property: list[str] :ivar record_property: @@ -61,7 +41,7 @@ class Model(TypedDict, total=False): :ivar float32_property: :vartype float32_property: float :ivar enum_property: "EnumValue1" - :vartype enum_property: str or ~specs.azure.example.basic.models.EnumEnum + :vartype enum_property: Union[str, "EnumEnum"] """ int32Property: int diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/pyproject.toml index 6cf64f058b15..f44e9d854d5a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/types.py deleted file mode 100644 index c56cde5f1669..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-payload-pageable/specs/azure/payload/pageable/types.py +++ /dev/null @@ -1,20 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing_extensions import Required, TypedDict - - -class User(TypedDict, total=False): - """User model. - - :ivar name: User name. Required. - :vartype name: str - """ - - name: Required[str] - """User name. Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/apiview-properties.json index 92db280a34a7..3bf4a8209e45 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/apiview-properties.json +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/apiview-properties.json @@ -3,9 +3,11 @@ "CrossLanguageDefinitionId": { "azure.resourcemanager.commonproperties.models.ApiError": "Azure.ResourceManager.CommonProperties.ApiError", "azure.resourcemanager.commonproperties.models.ApiErrorBase": "Azure.ResourceManager.CommonProperties.ApiErrorBase", - "azure.resourcemanager.commonproperties.models.CloudError": "Azure.ResourceManager.CommonProperties.CloudError", "azure.resourcemanager.commonproperties.models.Resource": "Azure.ResourceManager.CommonTypes.Resource", "azure.resourcemanager.commonproperties.models.TrackedResource": "Azure.ResourceManager.CommonTypes.TrackedResource", + "azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource": "Azure.ResourceManager.CommonProperties.ArmResourceIdentifierResource", + "azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResourceProperties": "Azure.ResourceManager.CommonProperties.ArmResourceIdentifierResourceProperties", + "azure.resourcemanager.commonproperties.models.CloudError": "Azure.ResourceManager.CommonProperties.CloudError", "azure.resourcemanager.commonproperties.models.ConfidentialResource": "Azure.ResourceManager.CommonProperties.ConfidentialResource", "azure.resourcemanager.commonproperties.models.ConfidentialResourceProperties": "Azure.ResourceManager.CommonProperties.ConfidentialResourceProperties", "azure.resourcemanager.commonproperties.models.ErrorAdditionalInfo": "Azure.ResourceManager.CommonTypes.ErrorAdditionalInfo", @@ -19,6 +21,7 @@ "azure.resourcemanager.commonproperties.models.UserAssignedIdentity": "Azure.ResourceManager.CommonTypes.UserAssignedIdentity", "azure.resourcemanager.commonproperties.models.CreatedByType": "Azure.ResourceManager.CommonTypes.createdByType", "azure.resourcemanager.commonproperties.models.ManagedServiceIdentityType": "Azure.ResourceManager.CommonTypes.ManagedServiceIdentityType", + "azure.resourcemanager.commonproperties.models.ResourceProvisioningState": "Azure.ResourceManager.ResourceProvisioningState", "azure.resourcemanager.commonproperties.operations.ManagedIdentityOperations.get": "Azure.ResourceManager.CommonProperties.ManagedIdentity.get", "azure.resourcemanager.commonproperties.aio.operations.ManagedIdentityOperations.get": "Azure.ResourceManager.CommonProperties.ManagedIdentity.get", "azure.resourcemanager.commonproperties.operations.ManagedIdentityOperations.create_with_system_assigned": "Azure.ResourceManager.CommonProperties.ManagedIdentity.createWithSystemAssigned", @@ -28,7 +31,11 @@ "azure.resourcemanager.commonproperties.operations.ErrorOperations.get_for_predefined_error": "Azure.ResourceManager.CommonProperties.Error.getForPredefinedError", "azure.resourcemanager.commonproperties.aio.operations.ErrorOperations.get_for_predefined_error": "Azure.ResourceManager.CommonProperties.Error.getForPredefinedError", "azure.resourcemanager.commonproperties.operations.ErrorOperations.create_for_user_defined_error": "Azure.ResourceManager.CommonProperties.Error.createForUserDefinedError", - "azure.resourcemanager.commonproperties.aio.operations.ErrorOperations.create_for_user_defined_error": "Azure.ResourceManager.CommonProperties.Error.createForUserDefinedError" + "azure.resourcemanager.commonproperties.aio.operations.ErrorOperations.create_for_user_defined_error": "Azure.ResourceManager.CommonProperties.Error.createForUserDefinedError", + "azure.resourcemanager.commonproperties.operations.ArmResourceIdentifiersOperations.get": "Azure.ResourceManager.CommonProperties.ArmResourceIdentifiers.get", + "azure.resourcemanager.commonproperties.aio.operations.ArmResourceIdentifiersOperations.get": "Azure.ResourceManager.CommonProperties.ArmResourceIdentifiers.get", + "azure.resourcemanager.commonproperties.operations.ArmResourceIdentifiersOperations.create_or_replace": "Azure.ResourceManager.CommonProperties.ArmResourceIdentifiers.createOrReplace", + "azure.resourcemanager.commonproperties.aio.operations.ArmResourceIdentifiersOperations.create_or_replace": "Azure.ResourceManager.CommonProperties.ArmResourceIdentifiers.createOrReplace" }, - "CrossLanguageVersion": "ad207ac2ccc3" + "CrossLanguageVersion": "f9b539c8f6ce" } \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_client.py index 9d8330cf4330..f7df9ddc15b8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_client.py @@ -19,7 +19,7 @@ from ._configuration import CommonPropertiesClientConfiguration from ._utils.serialization import Deserializer, Serializer -from .operations import ErrorOperations, ManagedIdentityOperations +from .operations import ArmResourceIdentifiersOperations, ErrorOperations, ManagedIdentityOperations if sys.version_info >= (3, 11): from typing import Self @@ -39,6 +39,9 @@ class CommonPropertiesClient: azure.resourcemanager.commonproperties.operations.ManagedIdentityOperations :ivar error: ErrorOperations operations :vartype error: azure.resourcemanager.commonproperties.operations.ErrorOperations + :ivar arm_resource_identifiers: ArmResourceIdentifiersOperations operations + :vartype arm_resource_identifiers: + azure.resourcemanager.commonproperties.operations.ArmResourceIdentifiersOperations :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. @@ -106,6 +109,9 @@ def __init__( self._client, self._config, self._serialize, self._deserialize ) self.error = ErrorOperations(self._client, self._config, self._serialize, self._deserialize) + self.arm_resource_identifiers = ArmResourceIdentifiersOperations( + self._client, self._config, self._serialize, self._deserialize + ) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/_client.py index 63514b9ddee4..70c23f86ff89 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/_client.py @@ -19,7 +19,7 @@ from .._utils.serialization import Deserializer, Serializer from ._configuration import CommonPropertiesClientConfiguration -from .operations import ErrorOperations, ManagedIdentityOperations +from .operations import ArmResourceIdentifiersOperations, ErrorOperations, ManagedIdentityOperations if sys.version_info >= (3, 11): from typing import Self @@ -39,6 +39,9 @@ class CommonPropertiesClient: azure.resourcemanager.commonproperties.aio.operations.ManagedIdentityOperations :ivar error: ErrorOperations operations :vartype error: azure.resourcemanager.commonproperties.aio.operations.ErrorOperations + :ivar arm_resource_identifiers: ArmResourceIdentifiersOperations operations + :vartype arm_resource_identifiers: + azure.resourcemanager.commonproperties.aio.operations.ArmResourceIdentifiersOperations :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. @@ -108,6 +111,9 @@ def __init__( self._client, self._config, self._serialize, self._deserialize ) self.error = ErrorOperations(self._client, self._config, self._serialize, self._deserialize) + self.arm_resource_identifiers = ArmResourceIdentifiersOperations( + self._client, self._config, self._serialize, self._deserialize + ) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/__init__.py index f406b6d443e4..2a057b552daf 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/__init__.py @@ -14,6 +14,7 @@ from ._operations import ManagedIdentityOperations # type: ignore from ._operations import ErrorOperations # type: ignore +from ._operations import ArmResourceIdentifiersOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -22,6 +23,7 @@ __all__ = [ "ManagedIdentityOperations", "ErrorOperations", + "ArmResourceIdentifiersOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/_operations.py index ae9f21e7824d..fa5d32f4f7bd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,10 +28,12 @@ from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( + build_arm_resource_identifiers_create_or_replace_request, + build_arm_resource_identifiers_get_request, build_error_create_for_user_defined_error_request, build_error_get_for_predefined_error_request, build_managed_identity_create_with_system_assigned_request, @@ -39,7 +42,6 @@ ) from .._configuration import CommonPropertiesClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -167,7 +169,7 @@ async def create_with_system_assigned( self, resource_group_name: str, managed_identity_tracked_resource_name: str, - resource: JSON, + resource: _types.ManagedIdentityTrackedResource, *, content_type: str = "application/json", **kwargs: Any @@ -180,7 +182,7 @@ async def create_with_system_assigned( :param managed_identity_tracked_resource_name: arm resource name for path. Required. :type managed_identity_tracked_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.commonproperties.types.ManagedIdentityTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -223,7 +225,7 @@ async def create_with_system_assigned( self, resource_group_name: str, managed_identity_tracked_resource_name: str, - resource: Union[_models.ManagedIdentityTrackedResource, JSON, IO[bytes]], + resource: Union[_models.ManagedIdentityTrackedResource, _types.ManagedIdentityTrackedResource, IO[bytes]], **kwargs: Any ) -> _models.ManagedIdentityTrackedResource: """Create a ManagedIdentityTrackedResource. @@ -233,10 +235,10 @@ async def create_with_system_assigned( :type resource_group_name: str :param managed_identity_tracked_resource_name: arm resource name for path. Required. :type managed_identity_tracked_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - ManagedIdentityTrackedResource, JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a ManagedIdentityTrackedResource type or + a IO[bytes] type. Required. :type resource: ~azure.resourcemanager.commonproperties.models.ManagedIdentityTrackedResource - or JSON or IO[bytes] + or ~azure.resourcemanager.commonproperties.types.ManagedIdentityTrackedResource or IO[bytes] :return: ManagedIdentityTrackedResource. The ManagedIdentityTrackedResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.commonproperties.models.ManagedIdentityTrackedResource @@ -342,7 +344,7 @@ async def update_with_user_assigned_and_system_assigned( # pylint: disable=name self, resource_group_name: str, managed_identity_tracked_resource_name: str, - properties: JSON, + properties: _types.ManagedIdentityTrackedResource, *, content_type: str = "application/json", **kwargs: Any @@ -355,7 +357,7 @@ async def update_with_user_assigned_and_system_assigned( # pylint: disable=name :param managed_identity_tracked_resource_name: arm resource name for path. Required. :type managed_identity_tracked_resource_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.commonproperties.types.ManagedIdentityTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -398,7 +400,7 @@ async def update_with_user_assigned_and_system_assigned( # pylint: disable=name self, resource_group_name: str, managed_identity_tracked_resource_name: str, - properties: Union[_models.ManagedIdentityTrackedResource, JSON, IO[bytes]], + properties: Union[_models.ManagedIdentityTrackedResource, _types.ManagedIdentityTrackedResource, IO[bytes]], **kwargs: Any ) -> _models.ManagedIdentityTrackedResource: """Update a ManagedIdentityTrackedResource. @@ -408,10 +410,10 @@ async def update_with_user_assigned_and_system_assigned( # pylint: disable=name :type resource_group_name: str :param managed_identity_tracked_resource_name: arm resource name for path. Required. :type managed_identity_tracked_resource_name: str - :param properties: The resource properties to be updated. Is one of the following types: - ManagedIdentityTrackedResource, JSON, IO[bytes] Required. + :param properties: The resource properties to be updated. Is either a + ManagedIdentityTrackedResource type or a IO[bytes] type. Required. :type properties: ~azure.resourcemanager.commonproperties.models.ManagedIdentityTrackedResource - or JSON or IO[bytes] + or ~azure.resourcemanager.commonproperties.types.ManagedIdentityTrackedResource or IO[bytes] :return: ManagedIdentityTrackedResource. The ManagedIdentityTrackedResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.commonproperties.models.ManagedIdentityTrackedResource @@ -606,7 +608,7 @@ async def create_for_user_defined_error( self, resource_group_name: str, confidential_resource_name: str, - resource: JSON, + resource: _types.ConfidentialResource, *, content_type: str = "application/json", **kwargs: Any @@ -619,7 +621,7 @@ async def create_for_user_defined_error( :param confidential_resource_name: The name of the ConfidentialResource. Required. :type confidential_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.commonproperties.types.ConfidentialResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -660,7 +662,7 @@ async def create_for_user_defined_error( self, resource_group_name: str, confidential_resource_name: str, - resource: Union[_models.ConfidentialResource, JSON, IO[bytes]], + resource: Union[_models.ConfidentialResource, _types.ConfidentialResource, IO[bytes]], **kwargs: Any ) -> _models.ConfidentialResource: """Create a ConfidentialResource. @@ -670,10 +672,10 @@ async def create_for_user_defined_error( :type resource_group_name: str :param confidential_resource_name: The name of the ConfidentialResource. Required. :type confidential_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - ConfidentialResource, JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.commonproperties.models.ConfidentialResource or JSON or - IO[bytes] + :param resource: Resource create parameters. Is either a ConfidentialResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.commonproperties.models.ConfidentialResource or + ~azure.resourcemanager.commonproperties.types.ConfidentialResource or IO[bytes] :return: ConfidentialResource. The ConfidentialResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.commonproperties.models.ConfidentialResource :raises ~azure.core.exceptions.HttpResponseError: @@ -744,3 +746,269 @@ async def create_for_user_defined_error( return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + +class ArmResourceIdentifiersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.resourcemanager.commonproperties.aio.CommonPropertiesClient`'s + :attr:`arm_resource_identifiers` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: CommonPropertiesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, arm_resource_identifier_resource_name: str, **kwargs: Any + ) -> _models.ArmResourceIdentifierResource: + """Get a ArmResourceIdentifierResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param arm_resource_identifier_resource_name: arm resource name for path. Required. + :type arm_resource_identifier_resource_name: str + :return: ArmResourceIdentifierResource. The ArmResourceIdentifierResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ArmResourceIdentifierResource] = kwargs.pop("cls", None) + + _request = build_arm_resource_identifiers_get_request( + resource_group_name=resource_group_name, + arm_resource_identifier_resource_name=arm_resource_identifier_resource_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ArmResourceIdentifierResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_replace( + self, + resource_group_name: str, + arm_resource_identifier_resource_name: str, + resource: _models.ArmResourceIdentifierResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ArmResourceIdentifierResource: + """Create a ArmResourceIdentifierResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param arm_resource_identifier_resource_name: arm resource name for path. Required. + :type arm_resource_identifier_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ArmResourceIdentifierResource. The ArmResourceIdentifierResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_replace( + self, + resource_group_name: str, + arm_resource_identifier_resource_name: str, + resource: _types.ArmResourceIdentifierResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ArmResourceIdentifierResource: + """Create a ArmResourceIdentifierResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param arm_resource_identifier_resource_name: arm resource name for path. Required. + :type arm_resource_identifier_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.resourcemanager.commonproperties.types.ArmResourceIdentifierResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ArmResourceIdentifierResource. The ArmResourceIdentifierResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_replace( + self, + resource_group_name: str, + arm_resource_identifier_resource_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ArmResourceIdentifierResource: + """Create a ArmResourceIdentifierResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param arm_resource_identifier_resource_name: arm resource name for path. Required. + :type arm_resource_identifier_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ArmResourceIdentifierResource. The ArmResourceIdentifierResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_replace( + self, + resource_group_name: str, + arm_resource_identifier_resource_name: str, + resource: Union[_models.ArmResourceIdentifierResource, _types.ArmResourceIdentifierResource, IO[bytes]], + **kwargs: Any + ) -> _models.ArmResourceIdentifierResource: + """Create a ArmResourceIdentifierResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param arm_resource_identifier_resource_name: arm resource name for path. Required. + :type arm_resource_identifier_resource_name: str + :param resource: Resource create parameters. Is either a ArmResourceIdentifierResource type or + a IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource or + ~azure.resourcemanager.commonproperties.types.ArmResourceIdentifierResource or IO[bytes] + :return: ArmResourceIdentifierResource. The ArmResourceIdentifierResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ArmResourceIdentifierResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_arm_resource_identifiers_create_or_replace_request( + resource_group_name=resource_group_name, + arm_resource_identifier_resource_name=arm_resource_identifier_resource_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ArmResourceIdentifierResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/__init__.py index 3eff4d970946..5d0f3b8c04cc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/__init__.py @@ -16,6 +16,8 @@ from ._models import ( # type: ignore ApiError, ApiErrorBase, + ArmResourceIdentifierResource, + ArmResourceIdentifierResourceProperties, CloudError, ConfidentialResource, ConfidentialResourceProperties, @@ -35,6 +37,7 @@ from ._enums import ( # type: ignore CreatedByType, ManagedServiceIdentityType, + ResourceProvisioningState, ) from ._patch import __all__ as _patch_all from ._patch import * @@ -43,6 +46,8 @@ __all__ = [ "ApiError", "ApiErrorBase", + "ArmResourceIdentifierResource", + "ArmResourceIdentifierResourceProperties", "CloudError", "ConfidentialResource", "ConfidentialResourceProperties", @@ -59,6 +64,7 @@ "UserAssignedIdentity", "CreatedByType", "ManagedServiceIdentityType", + "ResourceProvisioningState", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_enums.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_enums.py index 52e7a7167bb6..557b4e886532 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_enums.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_enums.py @@ -36,3 +36,14 @@ class ManagedServiceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """User assigned managed identity.""" SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned,UserAssigned" """System and user assigned managed identity.""" + + +class ResourceProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state of a resource type.""" + + SUCCEEDED = "Succeeded" + """Resource has been created.""" + FAILED = "Failed" + """Resource creation failed.""" + CANCELED = "Canceled" + """Resource creation was canceled.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_models.py index f03e1f5e0330..156176664dcd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_models.py @@ -105,34 +105,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class CloudError(_Model): - """An error response. - - :ivar error: Api error. - :vartype error: ~azure.resourcemanager.commonproperties.models.ApiError - """ - - error: Optional["_models.ApiError"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Api error.""" - - @overload - def __init__( - self, - *, - error: Optional["_models.ApiError"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - class Resource(_Model): """Resource. @@ -205,6 +177,139 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class ArmResourceIdentifierResource(TrackedResource): + """Concrete tracked resource types can be created by aliasing this type using a specific property + type. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.resourcemanager.commonproperties.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar properties: The resource-specific properties for this resource. + :vartype properties: + ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResourceProperties + """ + + properties: Optional["_models.ArmResourceIdentifierResourceProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The resource-specific properties for this resource.""" + + @overload + def __init__( + self, + *, + location: str, + tags: Optional[dict[str, str]] = None, + properties: Optional["_models.ArmResourceIdentifierResourceProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ArmResourceIdentifierResourceProperties(_Model): + """ArmResourceIdentifier Resource Properties. + + :ivar provisioning_state: The status of the last operation. Required. Known values are: + "Succeeded", "Failed", and "Canceled". + :vartype provisioning_state: str or + ~azure.resourcemanager.commonproperties.models.ResourceProvisioningState + :ivar simple_arm_id: A basic ARM resource identifier without type or scopes. Required. + :vartype simple_arm_id: str + :ivar arm_id_with_type: An ARM resource identifier with type only. Required. + :vartype arm_id_with_type: str + :ivar arm_id_with_type_and_scope: An ARM resource identifier with type and scopes. Required. + :vartype arm_id_with_type_and_scope: str + :ivar arm_id_with_all_scopes: An ARM resource identifier with all scopes. Required. + :vartype arm_id_with_all_scopes: str + """ + + provisioning_state: Union[str, "_models.ResourceProvisioningState"] = rest_field( + name="provisioningState", visibility=["read"] + ) + """The status of the last operation. Required. Known values are: \"Succeeded\", \"Failed\", and + \"Canceled\".""" + simple_arm_id: str = rest_field(name="simpleArmId", visibility=["read", "create", "update", "delete", "query"]) + """A basic ARM resource identifier without type or scopes. Required.""" + arm_id_with_type: str = rest_field(name="armIdWithType", visibility=["read", "create", "update", "delete", "query"]) + """An ARM resource identifier with type only. Required.""" + arm_id_with_type_and_scope: str = rest_field( + name="armIdWithTypeAndScope", visibility=["read", "create", "update", "delete", "query"] + ) + """An ARM resource identifier with type and scopes. Required.""" + arm_id_with_all_scopes: str = rest_field( + name="armIdWithAllScopes", visibility=["read", "create", "update", "delete", "query"] + ) + """An ARM resource identifier with all scopes. Required.""" + + @overload + def __init__( + self, + *, + simple_arm_id: str, + arm_id_with_type: str, + arm_id_with_type_and_scope: str, + arm_id_with_all_scopes: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CloudError(_Model): + """An error response. + + :ivar error: Api error. + :vartype error: ~azure.resourcemanager.commonproperties.models.ApiError + """ + + error: Optional["_models.ApiError"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Api error.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.ApiError"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class ConfidentialResource(TrackedResource): """Concrete tracked resource types can be created by aliasing this type using a specific property type. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/__init__.py index f406b6d443e4..2a057b552daf 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/__init__.py @@ -14,6 +14,7 @@ from ._operations import ManagedIdentityOperations # type: ignore from ._operations import ErrorOperations # type: ignore +from ._operations import ArmResourceIdentifiersOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -22,6 +23,7 @@ __all__ = [ "ManagedIdentityOperations", "ErrorOperations", + "ArmResourceIdentifiersOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/_operations.py index 89b8e596d31c..d52bc2ef0497 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=line-too-long,useless-suppression +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -28,12 +28,11 @@ from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import CommonPropertiesClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -196,6 +195,69 @@ def build_error_create_for_user_defined_error_request( # pylint: disable=name-t return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) +def build_arm_resource_identifiers_get_request( # pylint: disable=name-too-long + resource_group_name: str, arm_resource_identifier_resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-12-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.CommonProperties/armResourceIdentifierResources/{armResourceIdentifierResourceName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "armResourceIdentifierResourceName": _SERIALIZER.url( + "arm_resource_identifier_resource_name", arm_resource_identifier_resource_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_arm_resource_identifiers_create_or_replace_request( # pylint: disable=name-too-long + resource_group_name: str, arm_resource_identifier_resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-12-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.CommonProperties/armResourceIdentifierResources/{armResourceIdentifierResourceName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "armResourceIdentifierResourceName": _SERIALIZER.url( + "arm_resource_identifier_resource_name", arm_resource_identifier_resource_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + class ManagedIdentityOperations: """ .. warning:: @@ -319,7 +381,7 @@ def create_with_system_assigned( self, resource_group_name: str, managed_identity_tracked_resource_name: str, - resource: JSON, + resource: _types.ManagedIdentityTrackedResource, *, content_type: str = "application/json", **kwargs: Any @@ -332,7 +394,7 @@ def create_with_system_assigned( :param managed_identity_tracked_resource_name: arm resource name for path. Required. :type managed_identity_tracked_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.commonproperties.types.ManagedIdentityTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -375,7 +437,7 @@ def create_with_system_assigned( self, resource_group_name: str, managed_identity_tracked_resource_name: str, - resource: Union[_models.ManagedIdentityTrackedResource, JSON, IO[bytes]], + resource: Union[_models.ManagedIdentityTrackedResource, _types.ManagedIdentityTrackedResource, IO[bytes]], **kwargs: Any ) -> _models.ManagedIdentityTrackedResource: """Create a ManagedIdentityTrackedResource. @@ -385,10 +447,10 @@ def create_with_system_assigned( :type resource_group_name: str :param managed_identity_tracked_resource_name: arm resource name for path. Required. :type managed_identity_tracked_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - ManagedIdentityTrackedResource, JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a ManagedIdentityTrackedResource type or + a IO[bytes] type. Required. :type resource: ~azure.resourcemanager.commonproperties.models.ManagedIdentityTrackedResource - or JSON or IO[bytes] + or ~azure.resourcemanager.commonproperties.types.ManagedIdentityTrackedResource or IO[bytes] :return: ManagedIdentityTrackedResource. The ManagedIdentityTrackedResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.commonproperties.models.ManagedIdentityTrackedResource @@ -494,7 +556,7 @@ def update_with_user_assigned_and_system_assigned( # pylint: disable=name-too-l self, resource_group_name: str, managed_identity_tracked_resource_name: str, - properties: JSON, + properties: _types.ManagedIdentityTrackedResource, *, content_type: str = "application/json", **kwargs: Any @@ -507,7 +569,7 @@ def update_with_user_assigned_and_system_assigned( # pylint: disable=name-too-l :param managed_identity_tracked_resource_name: arm resource name for path. Required. :type managed_identity_tracked_resource_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.commonproperties.types.ManagedIdentityTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -550,7 +612,7 @@ def update_with_user_assigned_and_system_assigned( # pylint: disable=name-too-l self, resource_group_name: str, managed_identity_tracked_resource_name: str, - properties: Union[_models.ManagedIdentityTrackedResource, JSON, IO[bytes]], + properties: Union[_models.ManagedIdentityTrackedResource, _types.ManagedIdentityTrackedResource, IO[bytes]], **kwargs: Any ) -> _models.ManagedIdentityTrackedResource: """Update a ManagedIdentityTrackedResource. @@ -560,10 +622,10 @@ def update_with_user_assigned_and_system_assigned( # pylint: disable=name-too-l :type resource_group_name: str :param managed_identity_tracked_resource_name: arm resource name for path. Required. :type managed_identity_tracked_resource_name: str - :param properties: The resource properties to be updated. Is one of the following types: - ManagedIdentityTrackedResource, JSON, IO[bytes] Required. + :param properties: The resource properties to be updated. Is either a + ManagedIdentityTrackedResource type or a IO[bytes] type. Required. :type properties: ~azure.resourcemanager.commonproperties.models.ManagedIdentityTrackedResource - or JSON or IO[bytes] + or ~azure.resourcemanager.commonproperties.types.ManagedIdentityTrackedResource or IO[bytes] :return: ManagedIdentityTrackedResource. The ManagedIdentityTrackedResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.commonproperties.models.ManagedIdentityTrackedResource @@ -758,7 +820,7 @@ def create_for_user_defined_error( self, resource_group_name: str, confidential_resource_name: str, - resource: JSON, + resource: _types.ConfidentialResource, *, content_type: str = "application/json", **kwargs: Any @@ -771,7 +833,7 @@ def create_for_user_defined_error( :param confidential_resource_name: The name of the ConfidentialResource. Required. :type confidential_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.commonproperties.types.ConfidentialResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -812,7 +874,7 @@ def create_for_user_defined_error( self, resource_group_name: str, confidential_resource_name: str, - resource: Union[_models.ConfidentialResource, JSON, IO[bytes]], + resource: Union[_models.ConfidentialResource, _types.ConfidentialResource, IO[bytes]], **kwargs: Any ) -> _models.ConfidentialResource: """Create a ConfidentialResource. @@ -822,10 +884,10 @@ def create_for_user_defined_error( :type resource_group_name: str :param confidential_resource_name: The name of the ConfidentialResource. Required. :type confidential_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - ConfidentialResource, JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.commonproperties.models.ConfidentialResource or JSON or - IO[bytes] + :param resource: Resource create parameters. Is either a ConfidentialResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.commonproperties.models.ConfidentialResource or + ~azure.resourcemanager.commonproperties.types.ConfidentialResource or IO[bytes] :return: ConfidentialResource. The ConfidentialResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.commonproperties.models.ConfidentialResource :raises ~azure.core.exceptions.HttpResponseError: @@ -896,3 +958,269 @@ def create_for_user_defined_error( return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + +class ArmResourceIdentifiersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.resourcemanager.commonproperties.CommonPropertiesClient`'s + :attr:`arm_resource_identifiers` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: CommonPropertiesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, arm_resource_identifier_resource_name: str, **kwargs: Any + ) -> _models.ArmResourceIdentifierResource: + """Get a ArmResourceIdentifierResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param arm_resource_identifier_resource_name: arm resource name for path. Required. + :type arm_resource_identifier_resource_name: str + :return: ArmResourceIdentifierResource. The ArmResourceIdentifierResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ArmResourceIdentifierResource] = kwargs.pop("cls", None) + + _request = build_arm_resource_identifiers_get_request( + resource_group_name=resource_group_name, + arm_resource_identifier_resource_name=arm_resource_identifier_resource_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ArmResourceIdentifierResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_replace( + self, + resource_group_name: str, + arm_resource_identifier_resource_name: str, + resource: _models.ArmResourceIdentifierResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ArmResourceIdentifierResource: + """Create a ArmResourceIdentifierResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param arm_resource_identifier_resource_name: arm resource name for path. Required. + :type arm_resource_identifier_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ArmResourceIdentifierResource. The ArmResourceIdentifierResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_replace( + self, + resource_group_name: str, + arm_resource_identifier_resource_name: str, + resource: _types.ArmResourceIdentifierResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ArmResourceIdentifierResource: + """Create a ArmResourceIdentifierResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param arm_resource_identifier_resource_name: arm resource name for path. Required. + :type arm_resource_identifier_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.resourcemanager.commonproperties.types.ArmResourceIdentifierResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ArmResourceIdentifierResource. The ArmResourceIdentifierResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_replace( + self, + resource_group_name: str, + arm_resource_identifier_resource_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ArmResourceIdentifierResource: + """Create a ArmResourceIdentifierResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param arm_resource_identifier_resource_name: arm resource name for path. Required. + :type arm_resource_identifier_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ArmResourceIdentifierResource. The ArmResourceIdentifierResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_replace( + self, + resource_group_name: str, + arm_resource_identifier_resource_name: str, + resource: Union[_models.ArmResourceIdentifierResource, _types.ArmResourceIdentifierResource, IO[bytes]], + **kwargs: Any + ) -> _models.ArmResourceIdentifierResource: + """Create a ArmResourceIdentifierResource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param arm_resource_identifier_resource_name: arm resource name for path. Required. + :type arm_resource_identifier_resource_name: str + :param resource: Resource create parameters. Is either a ArmResourceIdentifierResource type or + a IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource or + ~azure.resourcemanager.commonproperties.types.ArmResourceIdentifierResource or IO[bytes] + :return: ArmResourceIdentifierResource. The ArmResourceIdentifierResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.commonproperties.models.ArmResourceIdentifierResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ArmResourceIdentifierResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_arm_resource_identifiers_create_or_replace_request( + resource_group_name=resource_group_name, + arm_resource_identifier_resource_name=arm_resource_identifier_resource_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ArmResourceIdentifierResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/types.py index 89507752adbd..a0aecd3340fd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/azure/resourcemanager/commonproperties/types.py @@ -7,69 +7,11 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -from typing import Any, TYPE_CHECKING, Union +from typing import TYPE_CHECKING, Union from typing_extensions import Required, TypedDict if TYPE_CHECKING: - from .models import CreatedByType, ManagedServiceIdentityType - - -class ApiError(TypedDict, total=False): - """Api error. - - :ivar details: The Api error details. - :vartype details: list[~azure.resourcemanager.commonproperties.models.ApiErrorBase] - :ivar innererror: The Api inner error. - :vartype innererror: ~azure.resourcemanager.commonproperties.models.InnerError - :ivar code: The error code. - :vartype code: str - :ivar target: The target of the particular error. - :vartype target: str - :ivar message: The error message. - :vartype message: str - """ - - details: list["ApiErrorBase"] - """The Api error details.""" - innererror: "InnerError" - """The Api inner error.""" - code: str - """The error code.""" - target: str - """The target of the particular error.""" - message: str - """The error message.""" - - -class ApiErrorBase(TypedDict, total=False): - """Api error base. - - :ivar code: The error code. - :vartype code: str - :ivar target: The target of the particular error. - :vartype target: str - :ivar message: The error message. - :vartype message: str - """ - - code: str - """The error code.""" - target: str - """The target of the particular error.""" - message: str - """The error message.""" - - -class CloudError(TypedDict, total=False): - """An error response. - - :ivar error: Api error. - :vartype error: ~azure.resourcemanager.commonproperties.models.ApiError - """ - - error: "ApiError" - """Api error.""" + from .models import CreatedByType, ManagedServiceIdentityType, ResourceProvisioningState class Resource(TypedDict, total=False): @@ -85,7 +27,7 @@ class Resource(TypedDict, total=False): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.commonproperties.models.SystemData + :vartype system_data: "SystemData" """ id: str @@ -113,7 +55,7 @@ class TrackedResource(Resource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.commonproperties.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. @@ -126,6 +68,62 @@ class TrackedResource(Resource): """The geo-location where the resource lives. Required.""" +class ArmResourceIdentifierResource(TrackedResource): + """Concrete tracked resource types can be created by aliasing this type using a specific property + type. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: "SystemData" + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar properties: The resource-specific properties for this resource. + :vartype properties: "ArmResourceIdentifierResourceProperties" + """ + + properties: "ArmResourceIdentifierResourceProperties" + """The resource-specific properties for this resource.""" + + +class ArmResourceIdentifierResourceProperties(TypedDict, total=False): + """ArmResourceIdentifier Resource Properties. + + :ivar provisioning_state: The status of the last operation. Required. Known values are: + "Succeeded", "Failed", and "Canceled". + :vartype provisioning_state: Union[str, "ResourceProvisioningState"] + :ivar simple_arm_id: A basic ARM resource identifier without type or scopes. Required. + :vartype simple_arm_id: str + :ivar arm_id_with_type: An ARM resource identifier with type only. Required. + :vartype arm_id_with_type: str + :ivar arm_id_with_type_and_scope: An ARM resource identifier with type and scopes. Required. + :vartype arm_id_with_type_and_scope: str + :ivar arm_id_with_all_scopes: An ARM resource identifier with all scopes. Required. + :vartype arm_id_with_all_scopes: str + """ + + provisioningState: Required[Union[str, "ResourceProvisioningState"]] + """The status of the last operation. Required. Known values are: \"Succeeded\", \"Failed\", and + \"Canceled\".""" + simpleArmId: Required[str] + """A basic ARM resource identifier without type or scopes. Required.""" + armIdWithType: Required[str] + """An ARM resource identifier with type only. Required.""" + armIdWithTypeAndScope: Required[str] + """An ARM resource identifier with type and scopes. Required.""" + armIdWithAllScopes: Required[str] + """An ARM resource identifier with all scopes. Required.""" + + class ConfidentialResource(TrackedResource): """Concrete tracked resource types can be created by aliasing this type using a specific property type. @@ -140,14 +138,13 @@ class ConfidentialResource(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.commonproperties.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: - ~azure.resourcemanager.commonproperties.models.ConfidentialResourceProperties + :vartype properties: "ConfidentialResourceProperties" """ properties: "ConfidentialResourceProperties" @@ -169,75 +166,6 @@ class ConfidentialResourceProperties(TypedDict, total=False): """Required.""" -class ErrorAdditionalInfo(TypedDict, total=False): - """The resource management error additional info. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - type: str - """The additional info type.""" - info: Any - """The additional info.""" - - -class ErrorDetail(TypedDict, total=False): - """The error detail. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.resourcemanager.commonproperties.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.resourcemanager.commonproperties.models.ErrorAdditionalInfo] - """ - - code: str - """The error code.""" - message: str - """The error message.""" - target: str - """The error target.""" - details: list["ErrorDetail"] - """The error details.""" - additionalInfo: list["ErrorAdditionalInfo"] - """The error additional info.""" - - -class ErrorResponse(TypedDict, total=False): - """Error response. - - :ivar error: The error object. - :vartype error: ~azure.resourcemanager.commonproperties.models.ErrorDetail - """ - - error: "ErrorDetail" - """The error object.""" - - -class InnerError(TypedDict, total=False): - """Inner error details. - - :ivar exceptiontype: The exception type. - :vartype exceptiontype: str - :ivar errordetail: The internal error message or exception dump. - :vartype errordetail: str - """ - - exceptiontype: str - """The exception type.""" - errordetail: str - """The internal error message or exception dump.""" - - class ManagedIdentityTrackedResource(TrackedResource): """Concrete tracked resource types can be created by aliasing this type using a specific property type. @@ -252,16 +180,15 @@ class ManagedIdentityTrackedResource(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.commonproperties.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: - ~azure.resourcemanager.commonproperties.models.ManagedIdentityTrackedResourceProperties + :vartype properties: "ManagedIdentityTrackedResourceProperties" :ivar identity: The managed service identities assigned to this resource. - :vartype identity: ~azure.resourcemanager.commonproperties.models.ManagedServiceIdentity + :vartype identity: "ManagedServiceIdentity" """ properties: "ManagedIdentityTrackedResourceProperties" @@ -292,10 +219,9 @@ class ManagedServiceIdentity(TypedDict, total=False): :vartype tenant_id: str :ivar type: The type of managed identity assigned to this resource. Required. Known values are: "None", "SystemAssigned", "UserAssigned", and "SystemAssigned,UserAssigned". - :vartype type: str or ~azure.resourcemanager.commonproperties.models.ManagedServiceIdentityType + :vartype type: Union[str, "ManagedServiceIdentityType"] :ivar user_assigned_identities: The identities assigned to this resource by the user. - :vartype user_assigned_identities: dict[str, - ~azure.resourcemanager.commonproperties.models.UserAssignedIdentity] + :vartype user_assigned_identities: dict[str, "UserAssignedIdentity"] """ principalId: str @@ -318,17 +244,16 @@ class SystemData(TypedDict, total=False): :vartype created_by: str :ivar created_by_type: The type of identity that created the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or ~azure.resourcemanager.commonproperties.models.CreatedByType + :vartype created_by_type: Union[str, "CreatedByType"] :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime + :vartype created_at: str :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str :ivar last_modified_by_type: The type of identity that last modified the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or - ~azure.resourcemanager.commonproperties.models.CreatedByType + :vartype last_modified_by_type: Union[str, "CreatedByType"] :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime + :vartype last_modified_at: str """ createdBy: str @@ -336,14 +261,14 @@ class SystemData(TypedDict, total=False): createdByType: Union[str, "CreatedByType"] """The type of identity that created the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - createdAt: datetime.datetime + createdAt: str """The timestamp of resource creation (UTC).""" lastModifiedBy: str """The identity that last modified the resource.""" lastModifiedByType: Union[str, "CreatedByType"] """The type of identity that last modified the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - lastModifiedAt: datetime.datetime + lastModifiedAt: str """The timestamp of resource last modification (UTC).""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/generated_tests/test_common_properties_arm_resource_identifiers_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/generated_tests/test_common_properties_arm_resource_identifiers_operations.py new file mode 100644 index 000000000000..0765732c2e74 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/generated_tests/test_common_properties_arm_resource_identifiers_operations.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.resourcemanager.commonproperties import CommonPropertiesClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCommonPropertiesArmResourceIdentifiersOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CommonPropertiesClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_arm_resource_identifiers_get(self, resource_group): + response = self.client.arm_resource_identifiers.get( + resource_group_name=resource_group.name, + arm_resource_identifier_resource_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_arm_resource_identifiers_create_or_replace(self, resource_group): + response = self.client.arm_resource_identifiers.create_or_replace( + resource_group_name=resource_group.name, + arm_resource_identifier_resource_name="str", + resource={ + "location": "str", + "id": "str", + "name": "str", + "properties": { + "armIdWithAllScopes": "str", + "armIdWithType": "str", + "armIdWithTypeAndScope": "str", + "provisioningState": "str", + "simpleArmId": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/generated_tests/test_common_properties_arm_resource_identifiers_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/generated_tests/test_common_properties_arm_resource_identifiers_operations_async.py new file mode 100644 index 000000000000..4ade6da36afe --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/generated_tests/test_common_properties_arm_resource_identifiers_operations_async.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.resourcemanager.commonproperties.aio import CommonPropertiesClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCommonPropertiesArmResourceIdentifiersOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CommonPropertiesClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_arm_resource_identifiers_get(self, resource_group): + response = await self.client.arm_resource_identifiers.get( + resource_group_name=resource_group.name, + arm_resource_identifier_resource_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_arm_resource_identifiers_create_or_replace(self, resource_group): + response = await self.client.arm_resource_identifiers.create_or_replace( + resource_group_name=resource_group.name, + arm_resource_identifier_resource_name="str", + resource={ + "location": "str", + "id": "str", + "name": "str", + "properties": { + "armIdWithAllScopes": "str", + "armIdWithType": "str", + "armIdWithTypeAndScope": "str", + "provisioningState": "str", + "simpleArmId": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/pyproject.toml index a90f3d2bfc2a..0c50d1a03637 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-common-properties/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/operations/_operations.py index 22489213e242..555daadd9e83 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/operations/_operations.py @@ -121,7 +121,7 @@ async def _two6_k_initial( async def begin_two6_k( self, resource_group_name: str, large_header_name: str, **kwargs: Any ) -> AsyncLROPoller[_models.CancelResult]: - """A long-running resource action. + """two6_k. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/operations/_operations.py index f6500eb3da0a..70310032891a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/operations/_operations.py @@ -151,7 +151,7 @@ def _two6_k_initial(self, resource_group_name: str, large_header_name: str, **kw def begin_two6_k( self, resource_group_name: str, large_header_name: str, **kwargs: Any ) -> LROPoller[_models.CancelResult]: - """A long-running resource action. + """two6_k. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/types.py deleted file mode 100644 index 3213e4762765..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/azure/resourcemanager/largeheader/types.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any -from typing_extensions import Required, TypedDict - - -class CancelResult(TypedDict, total=False): - """CancelResult. - - :ivar succeeded: Required. - :vartype succeeded: bool - """ - - succeeded: Required[bool] - """Required.""" - - -class ErrorAdditionalInfo(TypedDict, total=False): - """The resource management error additional info. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - type: str - """The additional info type.""" - info: Any - """The additional info.""" - - -class ErrorDetail(TypedDict, total=False): - """The error detail. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.resourcemanager.largeheader.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.resourcemanager.largeheader.models.ErrorAdditionalInfo] - """ - - code: str - """The error code.""" - message: str - """The error message.""" - target: str - """The error target.""" - details: list["ErrorDetail"] - """The error details.""" - additionalInfo: list["ErrorAdditionalInfo"] - """The error additional info.""" - - -class ErrorResponse(TypedDict, total=False): - """Error response. - - :ivar error: The error object. - :vartype error: ~azure.resourcemanager.largeheader.models.ErrorDetail - """ - - error: "ErrorDetail" - """The error object.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/pyproject.toml index 2a30ee51ba35..d0c872a3d258 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-large-header/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/CHANGELOG.md new file mode 100644 index 000000000000..b957b2575b48 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (1970-01-01) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/LICENSE b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/MANIFEST.in b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/MANIFEST.in new file mode 100644 index 000000000000..8531031d7e22 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/MANIFEST.in @@ -0,0 +1,7 @@ +include *.md +include LICENSE +include azure/resourcemanager/managementgroup/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/resourcemanager/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/README.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/_metadata.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/_metadata.json new file mode 100644 index 000000000000..8a225627964b --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersion": "2023-12-01-preview", + "apiVersions": { + "Azure.ResourceManager.ManagementGroup": "2023-12-01-preview" + } +} \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/apiview-properties.json new file mode 100644 index 000000000000..4b00b9906be3 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/apiview-properties.json @@ -0,0 +1,26 @@ +{ + "CrossLanguagePackageId": "Azure.ResourceManager.ManagementGroup", + "CrossLanguageDefinitionId": { + "azure.resourcemanager.managementgroup.models.ErrorAdditionalInfo": "Azure.ResourceManager.CommonTypes.ErrorAdditionalInfo", + "azure.resourcemanager.managementgroup.models.ErrorDetail": "Azure.ResourceManager.CommonTypes.ErrorDetail", + "azure.resourcemanager.managementgroup.models.ErrorResponse": "Azure.ResourceManager.CommonTypes.ErrorResponse", + "azure.resourcemanager.managementgroup.models.Resource": "Azure.ResourceManager.CommonTypes.Resource", + "azure.resourcemanager.managementgroup.models.ExtensionResource": "Azure.ResourceManager.CommonTypes.ExtensionResource", + "azure.resourcemanager.managementgroup.models.ManagementGroupChildResource": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResource", + "azure.resourcemanager.managementgroup.models.ManagementGroupChildResourceProperties": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResourceProperties", + "azure.resourcemanager.managementgroup.models.SystemData": "Azure.ResourceManager.CommonTypes.SystemData", + "azure.resourcemanager.managementgroup.models.CreatedByType": "Azure.ResourceManager.CommonTypes.createdByType", + "azure.resourcemanager.managementgroup.models.ProvisioningState": "Azure.ResourceManager.ManagementGroup.ProvisioningState", + "azure.resourcemanager.managementgroup.operations.ManagementGroupChildResourcesOperations.get": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResources.get", + "azure.resourcemanager.managementgroup.aio.operations.ManagementGroupChildResourcesOperations.get": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResources.get", + "azure.resourcemanager.managementgroup.operations.ManagementGroupChildResourcesOperations.begin_create_or_update": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResources.createOrUpdate", + "azure.resourcemanager.managementgroup.aio.operations.ManagementGroupChildResourcesOperations.begin_create_or_update": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResources.createOrUpdate", + "azure.resourcemanager.managementgroup.operations.ManagementGroupChildResourcesOperations.update": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResources.update", + "azure.resourcemanager.managementgroup.aio.operations.ManagementGroupChildResourcesOperations.update": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResources.update", + "azure.resourcemanager.managementgroup.operations.ManagementGroupChildResourcesOperations.delete": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResources.delete", + "azure.resourcemanager.managementgroup.aio.operations.ManagementGroupChildResourcesOperations.delete": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResources.delete", + "azure.resourcemanager.managementgroup.operations.ManagementGroupChildResourcesOperations.list_by_management_group": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResources.listByManagementGroup", + "azure.resourcemanager.managementgroup.aio.operations.ManagementGroupChildResourcesOperations.list_by_management_group": "Azure.ResourceManager.ManagementGroup.ManagementGroupChildResources.listByManagementGroup" + }, + "CrossLanguageVersion": "f15d0d496982" +} \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/__init__.py new file mode 100644 index 000000000000..17efd9f982ab --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ManagementGroupClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementGroupClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_client.py new file mode 100644 index 000000000000..8c4f7a05aa83 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_client.py @@ -0,0 +1,139 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +import sys +from typing import Any, Optional, TYPE_CHECKING, cast + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from ._configuration import ManagementGroupClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import ManagementGroupChildResourcesOperations + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ManagementGroupClient: + """Arm Resource Provider management API. + + :ivar management_group_child_resources: ManagementGroupChildResourcesOperations operations + :vartype management_group_child_resources: + azure.resourcemanager.managementgroup.operations.ManagementGroupChildResourcesOperations + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param base_url: Service host. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are + "2023-12-01-preview" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ManagementGroupClientConfiguration( + credential=credential, + base_url=cast(str, base_url), + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, _endpoint), policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.management_group_child_resources = ManagementGroupChildResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_configuration.py new file mode 100644 index 000000000000..6b2f02b7c15f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class ManagementGroupClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ManagementGroupClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param base_url: Service host. Default value is "https://management.azure.com". + :type base_url: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are + "2023-12-01-preview" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + base_url: str = "https://management.azure.com", + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2023-12-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.credential = credential + self.base_url = base_url + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "resourcemanager-managementgroup/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_utils/__init__.py similarity index 75% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/types.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_utils/__init__.py index 70a993e90c00..8026245c2abc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-override/specs/azure/clientgenerator/core/override/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_utils/__init__.py @@ -1,13 +1,6 @@ -# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- - -from typing_extensions import TypedDict - - -class GroupParametersOptions(TypedDict, total=False): - """GroupParametersOptions.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_utils/model_base.py new file mode 100644 index 000000000000..0f2c5bdfe70f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_utils/model_base.py @@ -0,0 +1,1771 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null + +from azure.core.rest import HttpResponse + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on the mapping's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on the mapping's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: a set-like object providing a view on the mapping's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: The value for key if key is in the dictionary, else default. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if the dictionary is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from the dictionary. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Update the dictionary from a mapping or an iterable of key-value pairs. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: The value for key if key is in the dictionary, else default. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _serialize_duration(o, format) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass: dict[str, typing.Any] = {} + if args: + if isinstance(args[0], ET.Element): + dict_to_pass.update(self._init_from_xml(args[0])) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) + super().__init__(dict_to_pass) + + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + self, element: ET.Element + ) -> dict[str, typing.Any]: + """Deserialize an XML element into a dict mapping rest field names to values. + + :param ET.Element element: The XML element to deserialize from. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + existed_attr_keys: list[str] = [] + + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value.text if isinstance(value, ET.Element) else value) + except ValueError: + # for unknown value, return raw value + return value.text if isinstance(value, ET.Element) else value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +# pylint: disable=too-many-instance-attributes +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._is_optional = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + self._deserializer = deserializer + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + deserializer=deserializer, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) + wrapped_element = _create_xml_element( + element_name, + model_meta.get("prefix"), + _model_ns, + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + _set_xml_attribute(wrapped_element, k, v, prop_meta) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": _dict_ns, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": _items_ns, + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + _safe_register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_utils/serialization.py new file mode 100644 index 000000000000..75906e2eb77f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_utils/serialization.py @@ -0,0 +1,2175 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_version.py similarity index 89% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_types.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_version.py index 6a0c99464d6c..be71c81bd282 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/_version.py @@ -6,6 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Union - -NewUnion = Union[str, int] +VERSION = "1.0.0b1" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/__init__.py new file mode 100644 index 000000000000..d86d173c83e0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ManagementGroupClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementGroupClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/_client.py new file mode 100644 index 000000000000..78975321aed3 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/_client.py @@ -0,0 +1,143 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +import sys +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .._utils.serialization import Deserializer, Serializer +from ._configuration import ManagementGroupClientConfiguration +from .operations import ManagementGroupChildResourcesOperations + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementGroupClient: + """Arm Resource Provider management API. + + :ivar management_group_child_resources: ManagementGroupChildResourcesOperations operations + :vartype management_group_child_resources: + azure.resourcemanager.managementgroup.aio.operations.ManagementGroupChildResourcesOperations + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param base_url: Service host. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are + "2023-12-01-preview" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = ManagementGroupClientConfiguration( + credential=credential, + base_url=cast(str, base_url), + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, _endpoint), policies=_policies, **kwargs + ) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.management_group_child_resources = ManagementGroupChildResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/_configuration.py new file mode 100644 index 000000000000..02524a53f4ad --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/_configuration.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementGroupClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ManagementGroupClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param base_url: Service host. Default value is "https://management.azure.com". + :type base_url: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are + "2023-12-01-preview" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + base_url: str = "https://management.azure.com", + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2023-12-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.credential = credential + self.base_url = base_url + self.cloud_setting = cloud_setting + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "resourcemanager-managementgroup/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/operations/__init__.py new file mode 100644 index 000000000000..a341cb66fb0e --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ManagementGroupChildResourcesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementGroupChildResourcesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/operations/_operations.py new file mode 100644 index 000000000000..88c4b3492254 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/operations/_operations.py @@ -0,0 +1,707 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models, types as _types +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_management_group_child_resources_create_or_update_request, + build_management_group_child_resources_delete_request, + build_management_group_child_resources_get_request, + build_management_group_child_resources_list_by_management_group_request, + build_management_group_child_resources_update_request, +) +from .._configuration import ManagementGroupClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class ManagementGroupChildResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.resourcemanager.managementgroup.aio.ManagementGroupClient`'s + :attr:`management_group_child_resources` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ManagementGroupClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, management_group_id: str, management_group_child_resource_name: str, **kwargs: Any + ) -> _models.ManagementGroupChildResource: + """Get a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :return: ManagementGroupChildResource. The ManagementGroupChildResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ManagementGroupChildResource] = kwargs.pop("cls", None) + + _request = build_management_group_child_resources_get_request( + management_group_id=management_group_id, + management_group_child_resource_name=management_group_child_resource_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ManagementGroupChildResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_or_update_initial( + self, + management_group_id: str, + management_group_child_resource_name: str, + resource: Union[_models.ManagementGroupChildResource, _types.ManagementGroupChildResource, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_management_group_child_resources_create_or_update_request( + management_group_id=management_group_id, + management_group_child_resource_name=management_group_child_resource_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 201: + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + management_group_id: str, + management_group_child_resource_name: str, + resource: _models.ManagementGroupChildResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ManagementGroupChildResource]: + """Create a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ManagementGroupChildResource. The + ManagementGroupChildResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + management_group_id: str, + management_group_child_resource_name: str, + resource: _types.ManagementGroupChildResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ManagementGroupChildResource]: + """Create a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.resourcemanager.managementgroup.types.ManagementGroupChildResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ManagementGroupChildResource. The + ManagementGroupChildResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + management_group_id: str, + management_group_child_resource_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ManagementGroupChildResource]: + """Create a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ManagementGroupChildResource. The + ManagementGroupChildResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + management_group_id: str, + management_group_child_resource_name: str, + resource: Union[_models.ManagementGroupChildResource, _types.ManagementGroupChildResource, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ManagementGroupChildResource]: + """Create a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param resource: Resource create parameters. Is either a ManagementGroupChildResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource or + ~azure.resourcemanager.managementgroup.types.ManagementGroupChildResource or IO[bytes] + :return: An instance of AsyncLROPoller that returns ManagementGroupChildResource. The + ManagementGroupChildResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementGroupChildResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + management_group_id=management_group_id, + management_group_child_resource_name=management_group_child_resource_name, + resource=resource, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = _deserialize(_models.ManagementGroupChildResource, response.json()) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.ManagementGroupChildResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ManagementGroupChildResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + async def update( + self, + management_group_id: str, + management_group_child_resource_name: str, + properties: _models.ManagementGroupChildResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementGroupChildResource: + """Update a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementGroupChildResource. The ManagementGroupChildResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + management_group_id: str, + management_group_child_resource_name: str, + properties: _types.ManagementGroupChildResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementGroupChildResource: + """Update a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.resourcemanager.managementgroup.types.ManagementGroupChildResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementGroupChildResource. The ManagementGroupChildResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + management_group_id: str, + management_group_child_resource_name: str, + properties: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementGroupChildResource: + """Update a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementGroupChildResource. The ManagementGroupChildResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + management_group_id: str, + management_group_child_resource_name: str, + properties: Union[_models.ManagementGroupChildResource, _types.ManagementGroupChildResource, IO[bytes]], + **kwargs: Any + ) -> _models.ManagementGroupChildResource: + """Update a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param properties: The resource properties to be updated. Is either a + ManagementGroupChildResource type or a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource or + ~azure.resourcemanager.managementgroup.types.ManagementGroupChildResource or IO[bytes] + :return: ManagementGroupChildResource. The ManagementGroupChildResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementGroupChildResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(properties, (IOBase, bytes)): + _content = properties + else: + _content = json.dumps(properties, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_management_group_child_resources_update_request( + management_group_id=management_group_id, + management_group_child_resource_name=management_group_child_resource_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ManagementGroupChildResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, management_group_id: str, management_group_child_resource_name: str, **kwargs: Any) -> None: + """Delete a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_management_group_child_resources_delete_request( + management_group_id=management_group_id, + management_group_child_resource_name=management_group_child_resource_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list_by_management_group( + self, management_group_id: str, **kwargs: Any + ) -> AsyncItemPaged["_models.ManagementGroupChildResource"]: + """List ManagementGroupChildResource resources by scope. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :return: An iterator like instance of ManagementGroupChildResource + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models.ManagementGroupChildResource]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_management_group_child_resources_list_by_management_group_request( + management_group_id=management_group_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + list[_models.ManagementGroupChildResource], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/__init__.py similarity index 58% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_operations/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/__init__.py index d15db16e70ef..99749431832b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/__init__.py @@ -12,13 +12,37 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import _FirstClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import _SecondClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._models import ( # type: ignore + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + ExtensionResource, + ManagementGroupChildResource, + ManagementGroupChildResourceProperties, + Resource, + SystemData, +) + +from ._enums import ( # type: ignore + CreatedByType, + ProvisioningState, +) from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk -__all__ = [] +__all__ = [ + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "ExtensionResource", + "ManagementGroupChildResource", + "ManagementGroupChildResourceProperties", + "Resource", + "SystemData", + "CreatedByType", + "ProvisioningState", +] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/_enums.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/_enums.py new file mode 100644 index 000000000000..81672497c838 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/_enums.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The kind of entity that created the resource.""" + + USER = "User" + """The entity was created by a user.""" + APPLICATION = "Application" + """The entity was created by an application.""" + MANAGED_IDENTITY = "ManagedIdentity" + """The entity was created by a managed identity.""" + KEY = "Key" + """The entity was created by a key.""" + + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of ProvisioningState.""" + + SUCCEEDED = "Succeeded" + """Resource has been created.""" + FAILED = "Failed" + """Resource creation failed.""" + CANCELED = "Canceled" + """Resource creation was canceled.""" + PROVISIONING = "Provisioning" + """PROVISIONING.""" + UPDATING = "Updating" + """UPDATING.""" + DELETING = "Deleting" + """DELETING.""" + ACCEPTED = "Accepted" + """ACCEPTED.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/_models.py new file mode 100644 index 000000000000..0fc52ab8c0b8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/_models.py @@ -0,0 +1,283 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +import datetime +from typing import Any, Mapping, Optional, TYPE_CHECKING, Union, overload + +from .._utils.model_base import Model as _Model, rest_field + +if TYPE_CHECKING: + from .. import models as _models + + +class ErrorAdditionalInfo(_Model): + """The resource management error additional info. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + type: Optional[str] = rest_field(visibility=["read"]) + """The additional info type.""" + info: Optional[Any] = rest_field(visibility=["read"]) + """The additional info.""" + + +class ErrorDetail(_Model): + """The error detail. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.resourcemanager.managementgroup.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.resourcemanager.managementgroup.models.ErrorAdditionalInfo] + """ + + code: Optional[str] = rest_field(visibility=["read"]) + """The error code.""" + message: Optional[str] = rest_field(visibility=["read"]) + """The error message.""" + target: Optional[str] = rest_field(visibility=["read"]) + """The error target.""" + details: Optional[list["_models.ErrorDetail"]] = rest_field(visibility=["read"]) + """The error details.""" + additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = rest_field( + name="additionalInfo", visibility=["read"] + ) + """The error additional info.""" + + +class ErrorResponse(_Model): + """Error response. + + :ivar error: The error object. + :vartype error: ~azure.resourcemanager.managementgroup.models.ErrorDetail + """ + + error: Optional["_models.ErrorDetail"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error object.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.ErrorDetail"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Resource(_Model): + """Resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.resourcemanager.managementgroup.models.SystemData + """ + + id: Optional[str] = rest_field(visibility=["read"]) + """Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.""" + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the resource.""" + type: Optional[str] = rest_field(visibility=["read"]) + """The type of the resource. E.g. \"Microsoft.Compute/virtualMachines\" or + \"Microsoft.Storage/storageAccounts\".""" + system_data: Optional["_models.SystemData"] = rest_field(name="systemData", visibility=["read"]) + """Azure Resource Manager metadata containing createdBy and modifiedBy information.""" + + +class ExtensionResource(Resource): + """The base extension resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.resourcemanager.managementgroup.models.SystemData + """ + + +class ManagementGroupChildResource(ExtensionResource): + """Concrete extension resource types can be created by aliasing this type using a specific + property type. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.resourcemanager.managementgroup.models.SystemData + :ivar properties: The resource-specific properties for this resource. + :vartype properties: + ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResourceProperties + """ + + properties: Optional["_models.ManagementGroupChildResourceProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The resource-specific properties for this resource.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.ManagementGroupChildResourceProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ManagementGroupChildResourceProperties(_Model): + """ManagementGroupChildResource properties. + + :ivar description: The description of the resource. + :vartype description: str + :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", + "Failed", "Canceled", "Provisioning", "Updating", "Deleting", and "Accepted". + :vartype provisioning_state: str or + ~azure.resourcemanager.managementgroup.models.ProvisioningState + """ + + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the resource.""" + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read"] + ) + """The status of the last operation. Known values are: \"Succeeded\", \"Failed\", \"Canceled\", + \"Provisioning\", \"Updating\", \"Deleting\", and \"Accepted\".""" + + @overload + def __init__( + self, + *, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SystemData(_Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.resourcemanager.managementgroup.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or + ~azure.resourcemanager.managementgroup.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + created_by: Optional[str] = rest_field(name="createdBy", visibility=["read", "create", "update", "delete", "query"]) + """The identity that created the resource.""" + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = rest_field( + name="createdByType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of identity that created the resource. Known values are: \"User\", \"Application\", + \"ManagedIdentity\", and \"Key\".""" + created_at: Optional[datetime.datetime] = rest_field( + name="createdAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The timestamp of resource creation (UTC).""" + last_modified_by: Optional[str] = rest_field( + name="lastModifiedBy", visibility=["read", "create", "update", "delete", "query"] + ) + """The identity that last modified the resource.""" + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = rest_field( + name="lastModifiedByType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of identity that last modified the resource. Known values are: \"User\", + \"Application\", \"ManagedIdentity\", and \"Key\".""" + last_modified_at: Optional[datetime.datetime] = rest_field( + name="lastModifiedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The timestamp of resource last modification (UTC).""" + + @overload + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/operations/__init__.py new file mode 100644 index 000000000000..a341cb66fb0e --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ManagementGroupChildResourcesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementGroupChildResourcesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/operations/_operations.py new file mode 100644 index 000000000000..74651eb056f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/operations/_operations.py @@ -0,0 +1,846 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models, types as _types +from .._configuration import ManagementGroupClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_management_group_child_resources_get_request( # pylint: disable=name-too-long + management_group_id: str, management_group_child_resource_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-12-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.ManagementGroupChild/managementGroupChildResources/{managementGroupChildResourceName}" + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "managementGroupChildResourceName": _SERIALIZER.url( + "management_group_child_resource_name", management_group_child_resource_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_group_child_resources_create_or_update_request( # pylint: disable=name-too-long + management_group_id: str, management_group_child_resource_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-12-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.ManagementGroupChild/managementGroupChildResources/{managementGroupChildResourceName}" + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "managementGroupChildResourceName": _SERIALIZER.url( + "management_group_child_resource_name", management_group_child_resource_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_group_child_resources_update_request( # pylint: disable=name-too-long + management_group_id: str, management_group_child_resource_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-12-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.ManagementGroupChild/managementGroupChildResources/{managementGroupChildResourceName}" + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "managementGroupChildResourceName": _SERIALIZER.url( + "management_group_child_resource_name", management_group_child_resource_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_group_child_resources_delete_request( # pylint: disable=name-too-long + management_group_id: str, management_group_child_resource_name: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-12-01-preview")) + # Construct URL + _url = "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.ManagementGroupChild/managementGroupChildResources/{managementGroupChildResourceName}" + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "managementGroupChildResourceName": _SERIALIZER.url( + "management_group_child_resource_name", management_group_child_resource_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_group_child_resources_list_by_management_group_request( # pylint: disable=name-too-long + management_group_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-12-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.ManagementGroupChild/managementGroupChildResources" + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ManagementGroupChildResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.resourcemanager.managementgroup.ManagementGroupClient`'s + :attr:`management_group_child_resources` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ManagementGroupClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, management_group_id: str, management_group_child_resource_name: str, **kwargs: Any + ) -> _models.ManagementGroupChildResource: + """Get a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :return: ManagementGroupChildResource. The ManagementGroupChildResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ManagementGroupChildResource] = kwargs.pop("cls", None) + + _request = build_management_group_child_resources_get_request( + management_group_id=management_group_id, + management_group_child_resource_name=management_group_child_resource_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ManagementGroupChildResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_or_update_initial( + self, + management_group_id: str, + management_group_child_resource_name: str, + resource: Union[_models.ManagementGroupChildResource, _types.ManagementGroupChildResource, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_management_group_child_resources_create_or_update_request( + management_group_id=management_group_id, + management_group_child_resource_name=management_group_child_resource_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 201: + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + management_group_id: str, + management_group_child_resource_name: str, + resource: _models.ManagementGroupChildResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ManagementGroupChildResource]: + """Create a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ManagementGroupChildResource. The + ManagementGroupChildResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + management_group_id: str, + management_group_child_resource_name: str, + resource: _types.ManagementGroupChildResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ManagementGroupChildResource]: + """Create a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.resourcemanager.managementgroup.types.ManagementGroupChildResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ManagementGroupChildResource. The + ManagementGroupChildResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + management_group_id: str, + management_group_child_resource_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ManagementGroupChildResource]: + """Create a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ManagementGroupChildResource. The + ManagementGroupChildResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + management_group_id: str, + management_group_child_resource_name: str, + resource: Union[_models.ManagementGroupChildResource, _types.ManagementGroupChildResource, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ManagementGroupChildResource]: + """Create a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param resource: Resource create parameters. Is either a ManagementGroupChildResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource or + ~azure.resourcemanager.managementgroup.types.ManagementGroupChildResource or IO[bytes] + :return: An instance of LROPoller that returns ManagementGroupChildResource. The + ManagementGroupChildResource is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementGroupChildResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + management_group_id=management_group_id, + management_group_child_resource_name=management_group_child_resource_name, + resource=resource, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = _deserialize(_models.ManagementGroupChildResource, response.json()) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.ManagementGroupChildResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ManagementGroupChildResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + def update( + self, + management_group_id: str, + management_group_child_resource_name: str, + properties: _models.ManagementGroupChildResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementGroupChildResource: + """Update a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementGroupChildResource. The ManagementGroupChildResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + management_group_id: str, + management_group_child_resource_name: str, + properties: _types.ManagementGroupChildResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementGroupChildResource: + """Update a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.resourcemanager.managementgroup.types.ManagementGroupChildResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementGroupChildResource. The ManagementGroupChildResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + management_group_id: str, + management_group_child_resource_name: str, + properties: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementGroupChildResource: + """Update a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param properties: The resource properties to be updated. Required. + :type properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ManagementGroupChildResource. The ManagementGroupChildResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + management_group_id: str, + management_group_child_resource_name: str, + properties: Union[_models.ManagementGroupChildResource, _types.ManagementGroupChildResource, IO[bytes]], + **kwargs: Any + ) -> _models.ManagementGroupChildResource: + """Update a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :param properties: The resource properties to be updated. Is either a + ManagementGroupChildResource type or a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource or + ~azure.resourcemanager.managementgroup.types.ManagementGroupChildResource or IO[bytes] + :return: ManagementGroupChildResource. The ManagementGroupChildResource is compatible with + MutableMapping + :rtype: ~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementGroupChildResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(properties, (IOBase, bytes)): + _content = properties + else: + _content = json.dumps(properties, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_management_group_child_resources_update_request( + management_group_id=management_group_id, + management_group_child_resource_name=management_group_child_resource_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ManagementGroupChildResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, management_group_id: str, management_group_child_resource_name: str, **kwargs: Any + ) -> None: + """Delete a ManagementGroupChildResource. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :param management_group_child_resource_name: The name of the ManagementGroupChildResource. + Required. + :type management_group_child_resource_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_management_group_child_resources_delete_request( + management_group_id=management_group_id, + management_group_child_resource_name=management_group_child_resource_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list_by_management_group( + self, management_group_id: str, **kwargs: Any + ) -> ItemPaged["_models.ManagementGroupChildResource"]: + """List ManagementGroupChildResource resources by scope. + + :param management_group_id: The management group ID. Required. + :type management_group_id: str + :return: An iterator like instance of ManagementGroupChildResource + :rtype: + ~azure.core.paging.ItemPaged[~azure.resourcemanager.managementgroup.models.ManagementGroupChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[list[_models.ManagementGroupChildResource]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_management_group_child_resources_list_by_management_group_request( + management_group_id=management_group_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + list[_models.ManagementGroupChildResource], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/py.typed b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/types.py new file mode 100644 index 000000000000..58e629254007 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/azure/resourcemanager/managementgroup/types.py @@ -0,0 +1,134 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING, Union +from typing_extensions import TypedDict + +if TYPE_CHECKING: + from .models import CreatedByType, ProvisioningState + + +class Resource(TypedDict, total=False): + """Resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: "SystemData" + """ + + id: str + """Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.""" + name: str + """The name of the resource.""" + type: str + """The type of the resource. E.g. \"Microsoft.Compute/virtualMachines\" or + \"Microsoft.Storage/storageAccounts\".""" + systemData: "SystemData" + """Azure Resource Manager metadata containing createdBy and modifiedBy information.""" + + +class ExtensionResource(Resource): + """The base extension resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: "SystemData" + """ + + +class ManagementGroupChildResource(ExtensionResource): + """Concrete extension resource types can be created by aliasing this type using a specific + property type. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: "SystemData" + :ivar properties: The resource-specific properties for this resource. + :vartype properties: "ManagementGroupChildResourceProperties" + """ + + properties: "ManagementGroupChildResourceProperties" + """The resource-specific properties for this resource.""" + + +class ManagementGroupChildResourceProperties(TypedDict, total=False): + """ManagementGroupChildResource properties. + + :ivar description: The description of the resource. + :vartype description: str + :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", + "Failed", "Canceled", "Provisioning", "Updating", "Deleting", and "Accepted". + :vartype provisioning_state: Union[str, "ProvisioningState"] + """ + + description: str + """The description of the resource.""" + provisioningState: Union[str, "ProvisioningState"] + """The status of the last operation. Known values are: \"Succeeded\", \"Failed\", \"Canceled\", + \"Provisioning\", \"Updating\", \"Deleting\", and \"Accepted\".""" + + +class SystemData(TypedDict, total=False): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: Union[str, "CreatedByType"] + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: str + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: Union[str, "CreatedByType"] + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: str + """ + + createdBy: str + """The identity that created the resource.""" + createdByType: Union[str, "CreatedByType"] + """The type of identity that created the resource. Known values are: \"User\", \"Application\", + \"ManagedIdentity\", and \"Key\".""" + createdAt: str + """The timestamp of resource creation (UTC).""" + lastModifiedBy: str + """The identity that last modified the resource.""" + lastModifiedByType: Union[str, "CreatedByType"] + """The type of identity that last modified the resource. Known values are: \"User\", + \"Application\", \"ManagedIdentity\", and \"Key\".""" + lastModifiedAt: str + """The timestamp of resource last modification (UTC).""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/dev_requirements.txt b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/generated_tests/conftest.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/generated_tests/conftest.py new file mode 100644 index 000000000000..ca0fb23cf084 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + managementgroup_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + managementgroup_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + managementgroup_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + managementgroup_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroup_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroup_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroup_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroup_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/generated_tests/test_management_group_management_group_child_resources_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/generated_tests/test_management_group_management_group_child_resources_operations.py new file mode 100644 index 000000000000..e76dbeeb3467 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/generated_tests/test_management_group_management_group_child_resources_operations.py @@ -0,0 +1,101 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.resourcemanager.managementgroup import ManagementGroupClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupManagementGroupChildResourcesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_group_child_resources_get(self, resource_group): + response = self.client.management_group_child_resources.get( + management_group_id="str", + management_group_child_resource_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_group_child_resources_begin_create_or_update(self, resource_group): + response = self.client.management_group_child_resources.begin_create_or_update( + management_group_id="str", + management_group_child_resource_name="str", + resource={ + "id": "str", + "name": "str", + "properties": {"description": "str", "provisioningState": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_group_child_resources_update(self, resource_group): + response = self.client.management_group_child_resources.update( + management_group_id="str", + management_group_child_resource_name="str", + properties={ + "id": "str", + "name": "str", + "properties": {"description": "str", "provisioningState": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_group_child_resources_delete(self, resource_group): + response = self.client.management_group_child_resources.delete( + management_group_id="str", + management_group_child_resource_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_management_group_child_resources_list_by_management_group(self, resource_group): + response = self.client.management_group_child_resources.list_by_management_group( + management_group_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/generated_tests/test_management_group_management_group_child_resources_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/generated_tests/test_management_group_management_group_child_resources_operations_async.py new file mode 100644 index 000000000000..4201ef480933 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/generated_tests/test_management_group_management_group_child_resources_operations_async.py @@ -0,0 +1,104 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.resourcemanager.managementgroup.aio import ManagementGroupClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupManagementGroupChildResourcesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_group_child_resources_get(self, resource_group): + response = await self.client.management_group_child_resources.get( + management_group_id="str", + management_group_child_resource_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_group_child_resources_begin_create_or_update(self, resource_group): + response = await ( + await self.client.management_group_child_resources.begin_create_or_update( + management_group_id="str", + management_group_child_resource_name="str", + resource={ + "id": "str", + "name": "str", + "properties": {"description": "str", "provisioningState": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_group_child_resources_update(self, resource_group): + response = await self.client.management_group_child_resources.update( + management_group_id="str", + management_group_child_resource_name="str", + properties={ + "id": "str", + "name": "str", + "properties": {"description": "str", "provisioningState": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_group_child_resources_delete(self, resource_group): + response = await self.client.management_group_child_resources.delete( + management_group_id="str", + management_group_child_resource_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_management_group_child_resources_list_by_management_group(self, resource_group): + response = self.client.management_group_child_resources.list_by_management_group( + management_group_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/pyproject.toml new file mode 100644 index 000000000000..55f3ac1efca5 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-management-group/pyproject.toml @@ -0,0 +1,61 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-resourcemanager-managementgroup" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Managementgroup Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", +] +requires-python = ">=3.10" +keywords = ["azure", "azure sdk"] + +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "azure.resourcemanager.managementgroup._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.resourcemanager", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/operations/_operations.py index eb3425082707..601d3ae964c4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/operations/_operations.py @@ -31,7 +31,7 @@ from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -53,7 +53,6 @@ T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] List = list @@ -348,7 +347,7 @@ async def put( self, subscription_id: str, subscription_resource1_name: str, - resource: JSON, + resource: _types.SubscriptionResource1, *, content_type: str = "application/json", **kwargs: Any @@ -360,7 +359,7 @@ async def put( :param subscription_resource1_name: The name of the SubscriptionResource1. Required. :type subscription_resource1_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource1 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -400,7 +399,7 @@ async def put( self, subscription_id: str, subscription_resource1_name: str, - resource: Union[_models.SubscriptionResource1, JSON, IO[bytes]], + resource: Union[_models.SubscriptionResource1, _types.SubscriptionResource1, IO[bytes]], **kwargs: Any ) -> _models.SubscriptionResource1: """Create a SubscriptionResource1. @@ -409,10 +408,10 @@ async def put( :type subscription_id: str :param subscription_resource1_name: The name of the SubscriptionResource1. Required. :type subscription_resource1_name: str - :param resource: Resource create parameters. Is one of the following types: - SubscriptionResource1, JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a SubscriptionResource1 type or a + IO[bytes] type. Required. :type resource: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource1 or - JSON or IO[bytes] + ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource1 or IO[bytes] :return: SubscriptionResource1. The SubscriptionResource1 is compatible with MutableMapping :rtype: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource1 :raises ~azure.core.exceptions.HttpResponseError: @@ -659,7 +658,7 @@ async def put( self, subscription_id: str, subscription_resource2_name: str, - resource: JSON, + resource: _types.SubscriptionResource2, *, content_type: str = "application/json", **kwargs: Any @@ -671,7 +670,7 @@ async def put( :param subscription_resource2_name: The name of the SubscriptionResource2. Required. :type subscription_resource2_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -711,7 +710,7 @@ async def put( self, subscription_id: str, subscription_resource2_name: str, - resource: Union[_models.SubscriptionResource2, JSON, IO[bytes]], + resource: Union[_models.SubscriptionResource2, _types.SubscriptionResource2, IO[bytes]], **kwargs: Any ) -> _models.SubscriptionResource2: """Create a SubscriptionResource2. @@ -720,10 +719,10 @@ async def put( :type subscription_id: str :param subscription_resource2_name: The name of the SubscriptionResource2. Required. :type subscription_resource2_name: str - :param resource: Resource create parameters. Is one of the following types: - SubscriptionResource2, JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a SubscriptionResource2 type or a + IO[bytes] type. Required. :type resource: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource2 or - JSON or IO[bytes] + ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource2 or IO[bytes] :return: SubscriptionResource2. The SubscriptionResource2 is compatible with MutableMapping :rtype: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource2 :raises ~azure.core.exceptions.HttpResponseError: @@ -970,7 +969,7 @@ async def put( self, subscription_id: str, subscription_resource_name: str, - resource: JSON, + resource: _types.SubscriptionResource, *, content_type: str = "application/json", **kwargs: Any @@ -982,7 +981,7 @@ async def put( :param subscription_resource_name: The name of the SubscriptionResource. Required. :type subscription_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1022,7 +1021,7 @@ async def put( self, subscription_id: str, subscription_resource_name: str, - resource: Union[_models.SubscriptionResource, JSON, IO[bytes]], + resource: Union[_models.SubscriptionResource, _types.SubscriptionResource, IO[bytes]], **kwargs: Any ) -> _models.SubscriptionResource: """Create a SubscriptionResource. @@ -1031,10 +1030,10 @@ async def put( :type subscription_id: str :param subscription_resource_name: The name of the SubscriptionResource. Required. :type subscription_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - SubscriptionResource, JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource or JSON - or IO[bytes] + :param resource: Resource create parameters. Is either a SubscriptionResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource or + ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource or IO[bytes] :return: SubscriptionResource. The SubscriptionResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource :raises ~azure.core.exceptions.HttpResponseError: @@ -1284,7 +1283,7 @@ async def put( self, resource_group_name: str, resource_group_resource_name: str, - resource: JSON, + resource: _types.ResourceGroupResource, *, content_type: str = "application/json", **kwargs: Any @@ -1297,7 +1296,7 @@ async def put( :param resource_group_resource_name: The name of the ResourceGroupResource. Required. :type resource_group_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.methodsubscriptionid.types.ResourceGroupResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1338,7 +1337,7 @@ async def put( self, resource_group_name: str, resource_group_resource_name: str, - resource: Union[_models.ResourceGroupResource, JSON, IO[bytes]], + resource: Union[_models.ResourceGroupResource, _types.ResourceGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ResourceGroupResource: """Create a ResourceGroupResource. @@ -1348,10 +1347,10 @@ async def put( :type resource_group_name: str :param resource_group_resource_name: The name of the ResourceGroupResource. Required. :type resource_group_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - ResourceGroupResource, JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a ResourceGroupResource type or a + IO[bytes] type. Required. :type resource: ~azure.resourcemanager.methodsubscriptionid.models.ResourceGroupResource or - JSON or IO[bytes] + ~azure.resourcemanager.methodsubscriptionid.types.ResourceGroupResource or IO[bytes] :return: ResourceGroupResource. The ResourceGroupResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.methodsubscriptionid.models.ResourceGroupResource :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/operations/_operations.py index 67342765688c..9bf6f5215aa1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/operations/_operations.py @@ -30,14 +30,13 @@ from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import MethodSubscriptionIdClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from .._utils.serialization import Deserializer, Serializer T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] List = list _SERIALIZER = Serializer() @@ -675,7 +674,7 @@ def put( self, subscription_id: str, subscription_resource1_name: str, - resource: JSON, + resource: _types.SubscriptionResource1, *, content_type: str = "application/json", **kwargs: Any @@ -687,7 +686,7 @@ def put( :param subscription_resource1_name: The name of the SubscriptionResource1. Required. :type subscription_resource1_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource1 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -727,7 +726,7 @@ def put( self, subscription_id: str, subscription_resource1_name: str, - resource: Union[_models.SubscriptionResource1, JSON, IO[bytes]], + resource: Union[_models.SubscriptionResource1, _types.SubscriptionResource1, IO[bytes]], **kwargs: Any ) -> _models.SubscriptionResource1: """Create a SubscriptionResource1. @@ -736,10 +735,10 @@ def put( :type subscription_id: str :param subscription_resource1_name: The name of the SubscriptionResource1. Required. :type subscription_resource1_name: str - :param resource: Resource create parameters. Is one of the following types: - SubscriptionResource1, JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a SubscriptionResource1 type or a + IO[bytes] type. Required. :type resource: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource1 or - JSON or IO[bytes] + ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource1 or IO[bytes] :return: SubscriptionResource1. The SubscriptionResource1 is compatible with MutableMapping :rtype: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource1 :raises ~azure.core.exceptions.HttpResponseError: @@ -988,7 +987,7 @@ def put( self, subscription_id: str, subscription_resource2_name: str, - resource: JSON, + resource: _types.SubscriptionResource2, *, content_type: str = "application/json", **kwargs: Any @@ -1000,7 +999,7 @@ def put( :param subscription_resource2_name: The name of the SubscriptionResource2. Required. :type subscription_resource2_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1040,7 +1039,7 @@ def put( self, subscription_id: str, subscription_resource2_name: str, - resource: Union[_models.SubscriptionResource2, JSON, IO[bytes]], + resource: Union[_models.SubscriptionResource2, _types.SubscriptionResource2, IO[bytes]], **kwargs: Any ) -> _models.SubscriptionResource2: """Create a SubscriptionResource2. @@ -1049,10 +1048,10 @@ def put( :type subscription_id: str :param subscription_resource2_name: The name of the SubscriptionResource2. Required. :type subscription_resource2_name: str - :param resource: Resource create parameters. Is one of the following types: - SubscriptionResource2, JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a SubscriptionResource2 type or a + IO[bytes] type. Required. :type resource: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource2 or - JSON or IO[bytes] + ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource2 or IO[bytes] :return: SubscriptionResource2. The SubscriptionResource2 is compatible with MutableMapping :rtype: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource2 :raises ~azure.core.exceptions.HttpResponseError: @@ -1299,7 +1298,7 @@ def put( self, subscription_id: str, subscription_resource_name: str, - resource: JSON, + resource: _types.SubscriptionResource, *, content_type: str = "application/json", **kwargs: Any @@ -1311,7 +1310,7 @@ def put( :param subscription_resource_name: The name of the SubscriptionResource. Required. :type subscription_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1351,7 +1350,7 @@ def put( self, subscription_id: str, subscription_resource_name: str, - resource: Union[_models.SubscriptionResource, JSON, IO[bytes]], + resource: Union[_models.SubscriptionResource, _types.SubscriptionResource, IO[bytes]], **kwargs: Any ) -> _models.SubscriptionResource: """Create a SubscriptionResource. @@ -1360,10 +1359,10 @@ def put( :type subscription_id: str :param subscription_resource_name: The name of the SubscriptionResource. Required. :type subscription_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - SubscriptionResource, JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource or JSON - or IO[bytes] + :param resource: Resource create parameters. Is either a SubscriptionResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource or + ~azure.resourcemanager.methodsubscriptionid.types.SubscriptionResource or IO[bytes] :return: SubscriptionResource. The SubscriptionResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource :raises ~azure.core.exceptions.HttpResponseError: @@ -1615,7 +1614,7 @@ def put( self, resource_group_name: str, resource_group_resource_name: str, - resource: JSON, + resource: _types.ResourceGroupResource, *, content_type: str = "application/json", **kwargs: Any @@ -1628,7 +1627,7 @@ def put( :param resource_group_resource_name: The name of the ResourceGroupResource. Required. :type resource_group_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.methodsubscriptionid.types.ResourceGroupResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1669,7 +1668,7 @@ def put( self, resource_group_name: str, resource_group_resource_name: str, - resource: Union[_models.ResourceGroupResource, JSON, IO[bytes]], + resource: Union[_models.ResourceGroupResource, _types.ResourceGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ResourceGroupResource: """Create a ResourceGroupResource. @@ -1679,10 +1678,10 @@ def put( :type resource_group_name: str :param resource_group_resource_name: The name of the ResourceGroupResource. Required. :type resource_group_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - ResourceGroupResource, JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a ResourceGroupResource type or a + IO[bytes] type. Required. :type resource: ~azure.resourcemanager.methodsubscriptionid.models.ResourceGroupResource or - JSON or IO[bytes] + ~azure.resourcemanager.methodsubscriptionid.types.ResourceGroupResource or IO[bytes] :return: ResourceGroupResource. The ResourceGroupResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.methodsubscriptionid.models.ResourceGroupResource :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/types.py index c60dcd94af68..c49dd0de397e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/azure/resourcemanager/methodsubscriptionid/types.py @@ -7,135 +7,11 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -from typing import Any, TYPE_CHECKING, Union +from typing import TYPE_CHECKING, Union from typing_extensions import Required, TypedDict if TYPE_CHECKING: - from .models import ActionType, CreatedByType, Origin, ResourceProvisioningState - - -class ErrorAdditionalInfo(TypedDict, total=False): - """The resource management error additional info. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - type: str - """The additional info type.""" - info: Any - """The additional info.""" - - -class ErrorDetail(TypedDict, total=False): - """The error detail. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.resourcemanager.methodsubscriptionid.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.resourcemanager.methodsubscriptionid.models.ErrorAdditionalInfo] - """ - - code: str - """The error code.""" - message: str - """The error message.""" - target: str - """The error target.""" - details: list["ErrorDetail"] - """The error details.""" - additionalInfo: list["ErrorAdditionalInfo"] - """The error additional info.""" - - -class ErrorResponse(TypedDict, total=False): - """Error response. - - :ivar error: The error object. - :vartype error: ~azure.resourcemanager.methodsubscriptionid.models.ErrorDetail - """ - - error: "ErrorDetail" - """The error object.""" - - -class Operation(TypedDict, total=False): - """REST API Operation. - - :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: - "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". - :vartype name: str - :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for - data-plane operations and "false" for Azure Resource Manager/control-plane operations. - :vartype is_data_action: bool - :ivar display: Localized display information for this particular operation. - :vartype display: ~azure.resourcemanager.methodsubscriptionid.models.OperationDisplay - :ivar origin: The intended executor of the operation; as in Resource Based Access Control - (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", - and "user,system". - :vartype origin: str or ~azure.resourcemanager.methodsubscriptionid.models.Origin - :ivar action_type: Extensible enum. Indicates the action type. "Internal" refers to actions - that are for internal only APIs. "Internal" - :vartype action_type: str or ~azure.resourcemanager.methodsubscriptionid.models.ActionType - """ - - name: str - """The name of the operation, as per Resource-Based Access Control (RBAC). Examples: - \"Microsoft.Compute/virtualMachines/write\", - \"Microsoft.Compute/virtualMachines/capture/action\".""" - isDataAction: bool - """Whether the operation applies to data-plane. This is \"true\" for data-plane operations and - \"false\" for Azure Resource Manager/control-plane operations.""" - display: "OperationDisplay" - """Localized display information for this particular operation.""" - origin: Union[str, "Origin"] - """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit - logs UX. Default value is \"user,system\". Known values are: \"user\", \"system\", and - \"user,system\".""" - actionType: Union[str, "ActionType"] - """Extensible enum. Indicates the action type. \"Internal\" refers to actions that are for - internal only APIs. \"Internal\"""" - - -class OperationDisplay(TypedDict, total=False): - """Localized display information for an operation. - - :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft - Monitoring Insights" or "Microsoft Compute". - :vartype provider: str - :ivar resource: The localized friendly name of the resource type related to this operation. - E.g. "Virtual Machines" or "Job Schedule Collections". - :vartype resource: str - :ivar operation: The concise, localized friendly name for the operation; suitable for - dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". - :vartype operation: str - :ivar description: The short, localized friendly description of the operation; suitable for - tool tips and detailed views. - :vartype description: str - """ - - provider: str - """The localized friendly form of the resource provider name, e.g. \"Microsoft Monitoring - Insights\" or \"Microsoft Compute\".""" - resource: str - """The localized friendly name of the resource type related to this operation. E.g. \"Virtual - Machines\" or \"Job Schedule Collections\".""" - operation: str - """The concise, localized friendly name for the operation; suitable for dropdowns. E.g. \"Create - or Update Virtual Machine\", \"Restart Virtual Machine\".""" - description: str - """The short, localized friendly description of the operation; suitable for tool tips and detailed - views.""" + from .models import CreatedByType, ResourceProvisioningState class Resource(TypedDict, total=False): @@ -151,7 +27,7 @@ class Resource(TypedDict, total=False): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.methodsubscriptionid.models.SystemData + :vartype system_data: "SystemData" """ id: str @@ -179,7 +55,7 @@ class ProxyResource(Resource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.methodsubscriptionid.models.SystemData + :vartype system_data: "SystemData" """ @@ -196,7 +72,7 @@ class TrackedResource(Resource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.methodsubscriptionid.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. @@ -223,14 +99,13 @@ class ResourceGroupResource(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.methodsubscriptionid.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: - ~azure.resourcemanager.methodsubscriptionid.models.ResourceGroupResourceProperties + :vartype properties: "ResourceGroupResourceProperties" """ properties: "ResourceGroupResourceProperties" @@ -242,8 +117,7 @@ class ResourceGroupResourceProperties(TypedDict, total=False): :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.resourcemanager.methodsubscriptionid.models.ResourceProvisioningState + :vartype provisioning_state: Union[str, "ResourceProvisioningState"] :ivar resource_group_setting: The resource group-scoped setting. :vartype resource_group_setting: str """ @@ -269,10 +143,9 @@ class SubscriptionResource(ProxyResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.methodsubscriptionid.models.SystemData + :vartype system_data: "SystemData" :ivar properties: The resource-specific properties for this resource. - :vartype properties: - ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResourceProperties + :vartype properties: "SubscriptionResourceProperties" """ properties: "SubscriptionResourceProperties" @@ -293,10 +166,9 @@ class SubscriptionResource1(ProxyResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.methodsubscriptionid.models.SystemData + :vartype system_data: "SystemData" :ivar properties: The resource-specific properties for this resource. - :vartype properties: - ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource1Properties + :vartype properties: "SubscriptionResource1Properties" """ properties: "SubscriptionResource1Properties" @@ -308,8 +180,7 @@ class SubscriptionResource1Properties(TypedDict, total=False): :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.resourcemanager.methodsubscriptionid.models.ResourceProvisioningState + :vartype provisioning_state: Union[str, "ResourceProvisioningState"] :ivar description: The description of the resource. :vartype description: str """ @@ -335,10 +206,9 @@ class SubscriptionResource2(ProxyResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.methodsubscriptionid.models.SystemData + :vartype system_data: "SystemData" :ivar properties: The resource-specific properties for this resource. - :vartype properties: - ~azure.resourcemanager.methodsubscriptionid.models.SubscriptionResource2Properties + :vartype properties: "SubscriptionResource2Properties" """ properties: "SubscriptionResource2Properties" @@ -350,8 +220,7 @@ class SubscriptionResource2Properties(TypedDict, total=False): :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.resourcemanager.methodsubscriptionid.models.ResourceProvisioningState + :vartype provisioning_state: Union[str, "ResourceProvisioningState"] :ivar config_value: The configuration value. :vartype config_value: str """ @@ -368,8 +237,7 @@ class SubscriptionResourceProperties(TypedDict, total=False): :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.resourcemanager.methodsubscriptionid.models.ResourceProvisioningState + :vartype provisioning_state: Union[str, "ResourceProvisioningState"] :ivar subscription_setting: The subscription-scoped setting. :vartype subscription_setting: str """ @@ -388,18 +256,16 @@ class SystemData(TypedDict, total=False): :vartype created_by: str :ivar created_by_type: The type of identity that created the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or - ~azure.resourcemanager.methodsubscriptionid.models.CreatedByType + :vartype created_by_type: Union[str, "CreatedByType"] :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime + :vartype created_at: str :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str :ivar last_modified_by_type: The type of identity that last modified the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or - ~azure.resourcemanager.methodsubscriptionid.models.CreatedByType + :vartype last_modified_by_type: Union[str, "CreatedByType"] :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime + :vartype last_modified_at: str """ createdBy: str @@ -407,12 +273,12 @@ class SystemData(TypedDict, total=False): createdByType: Union[str, "CreatedByType"] """The type of identity that created the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - createdAt: datetime.datetime + createdAt: str """The timestamp of resource creation (UTC).""" lastModifiedBy: str """The identity that last modified the resource.""" lastModifiedByType: Union[str, "CreatedByType"] """The type of identity that last modified the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - lastModifiedAt: datetime.datetime + lastModifiedAt: str """The timestamp of resource last modification (UTC).""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/pyproject.toml index cd973c646bbd..d35393e3c1b1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-method-subscription-id/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/operations/_operations.py index 51bdc03627b6..beea44eb10c0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/operations/_operations.py @@ -30,7 +30,7 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -41,7 +41,6 @@ ) from .._configuration import CombinedClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -138,7 +137,7 @@ async def _create_or_update_initial( self, resource_group_name: str, vm_name: str, - resource: Union[_models.VirtualMachine, JSON, IO[bytes]], + resource: Union[_models.VirtualMachine, _types.VirtualMachine, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -247,7 +246,7 @@ async def begin_create_or_update( self, resource_group_name: str, vm_name: str, - resource: JSON, + resource: _types.VirtualMachine, *, content_type: str = "application/json", **kwargs: Any @@ -261,7 +260,7 @@ async def begin_create_or_update( :param vm_name: The name of the VirtualMachine. Required. :type vm_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.multiservicesharedmodels.combined.types.VirtualMachine :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -307,7 +306,7 @@ async def begin_create_or_update( self, resource_group_name: str, vm_name: str, - resource: Union[_models.VirtualMachine, JSON, IO[bytes]], + resource: Union[_models.VirtualMachine, _types.VirtualMachine, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.VirtualMachine]: """The operation to create or update a virtual machine. Please note some properties can be set @@ -318,10 +317,10 @@ async def begin_create_or_update( :type resource_group_name: str :param vm_name: The name of the VirtualMachine. Required. :type vm_name: str - :param resource: Resource create parameters. Is one of the following types: VirtualMachine, - JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a VirtualMachine type or a IO[bytes] + type. Required. :type resource: ~azure.resourcemanager.multiservicesharedmodels.combined.models.VirtualMachine - or JSON or IO[bytes] + or ~azure.resourcemanager.multiservicesharedmodels.combined.types.VirtualMachine or IO[bytes] :return: An instance of AsyncLROPoller that returns VirtualMachine. The VirtualMachine is compatible with MutableMapping :rtype: @@ -475,7 +474,7 @@ async def _create_or_update_initial( self, resource_group_name: str, account_name: str, - resource: Union[_models.StorageAccount, JSON, IO[bytes]], + resource: Union[_models.StorageAccount, _types.StorageAccount, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -583,7 +582,7 @@ async def begin_create_or_update( self, resource_group_name: str, account_name: str, - resource: JSON, + resource: _types.StorageAccount, *, content_type: str = "application/json", **kwargs: Any @@ -596,7 +595,7 @@ async def begin_create_or_update( :param account_name: The name of the StorageAccount. Required. :type account_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.multiservicesharedmodels.combined.types.StorageAccount :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -641,7 +640,7 @@ async def begin_create_or_update( self, resource_group_name: str, account_name: str, - resource: Union[_models.StorageAccount, JSON, IO[bytes]], + resource: Union[_models.StorageAccount, _types.StorageAccount, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.StorageAccount]: """Creates or updates a storage account. @@ -651,10 +650,10 @@ async def begin_create_or_update( :type resource_group_name: str :param account_name: The name of the StorageAccount. Required. :type account_name: str - :param resource: Resource create parameters. Is one of the following types: StorageAccount, - JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a StorageAccount type or a IO[bytes] + type. Required. :type resource: ~azure.resourcemanager.multiservicesharedmodels.combined.models.StorageAccount - or JSON or IO[bytes] + or ~azure.resourcemanager.multiservicesharedmodels.combined.types.StorageAccount or IO[bytes] :return: An instance of AsyncLROPoller that returns StorageAccount. The StorageAccount is compatible with MutableMapping :rtype: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/operations/_operations.py index 517b78a902eb..5e1f4a474bb7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/operations/_operations.py @@ -30,12 +30,11 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import CombinedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -253,7 +252,7 @@ def _create_or_update_initial( self, resource_group_name: str, vm_name: str, - resource: Union[_models.VirtualMachine, JSON, IO[bytes]], + resource: Union[_models.VirtualMachine, _types.VirtualMachine, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -362,7 +361,7 @@ def begin_create_or_update( self, resource_group_name: str, vm_name: str, - resource: JSON, + resource: _types.VirtualMachine, *, content_type: str = "application/json", **kwargs: Any @@ -376,7 +375,7 @@ def begin_create_or_update( :param vm_name: The name of the VirtualMachine. Required. :type vm_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.multiservicesharedmodels.combined.types.VirtualMachine :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -422,7 +421,7 @@ def begin_create_or_update( self, resource_group_name: str, vm_name: str, - resource: Union[_models.VirtualMachine, JSON, IO[bytes]], + resource: Union[_models.VirtualMachine, _types.VirtualMachine, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.VirtualMachine]: """The operation to create or update a virtual machine. Please note some properties can be set @@ -433,10 +432,10 @@ def begin_create_or_update( :type resource_group_name: str :param vm_name: The name of the VirtualMachine. Required. :type vm_name: str - :param resource: Resource create parameters. Is one of the following types: VirtualMachine, - JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a VirtualMachine type or a IO[bytes] + type. Required. :type resource: ~azure.resourcemanager.multiservicesharedmodels.combined.models.VirtualMachine - or JSON or IO[bytes] + or ~azure.resourcemanager.multiservicesharedmodels.combined.types.VirtualMachine or IO[bytes] :return: An instance of LROPoller that returns VirtualMachine. The VirtualMachine is compatible with MutableMapping :rtype: @@ -590,7 +589,7 @@ def _create_or_update_initial( self, resource_group_name: str, account_name: str, - resource: Union[_models.StorageAccount, JSON, IO[bytes]], + resource: Union[_models.StorageAccount, _types.StorageAccount, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -698,7 +697,7 @@ def begin_create_or_update( self, resource_group_name: str, account_name: str, - resource: JSON, + resource: _types.StorageAccount, *, content_type: str = "application/json", **kwargs: Any @@ -711,7 +710,7 @@ def begin_create_or_update( :param account_name: The name of the StorageAccount. Required. :type account_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.multiservicesharedmodels.combined.types.StorageAccount :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -756,7 +755,7 @@ def begin_create_or_update( self, resource_group_name: str, account_name: str, - resource: Union[_models.StorageAccount, JSON, IO[bytes]], + resource: Union[_models.StorageAccount, _types.StorageAccount, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.StorageAccount]: """Creates or updates a storage account. @@ -766,10 +765,10 @@ def begin_create_or_update( :type resource_group_name: str :param account_name: The name of the StorageAccount. Required. :type account_name: str - :param resource: Resource create parameters. Is one of the following types: StorageAccount, - JSON, IO[bytes] Required. + :param resource: Resource create parameters. Is either a StorageAccount type or a IO[bytes] + type. Required. :type resource: ~azure.resourcemanager.multiservicesharedmodels.combined.models.StorageAccount - or JSON or IO[bytes] + or ~azure.resourcemanager.multiservicesharedmodels.combined.types.StorageAccount or IO[bytes] :return: An instance of LROPoller that returns StorageAccount. The StorageAccount is compatible with MutableMapping :rtype: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/types.py index 098ed04bc6b4..cfd5f1dea6ee 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/azure/resourcemanager/multiservicesharedmodels/combined/types.py @@ -7,69 +7,13 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -from typing import Any, TYPE_CHECKING, Union +from typing import TYPE_CHECKING, Union from typing_extensions import Required, TypedDict if TYPE_CHECKING: from .models import CreatedByType, ResourceProvisioningState -class ErrorAdditionalInfo(TypedDict, total=False): - """The resource management error additional info. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - type: str - """The additional info type.""" - info: Any - """The additional info.""" - - -class ErrorDetail(TypedDict, total=False): - """The error detail. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: - list[~azure.resourcemanager.multiservicesharedmodels.combined.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.resourcemanager.multiservicesharedmodels.combined.models.ErrorAdditionalInfo] - """ - - code: str - """The error code.""" - message: str - """The error message.""" - target: str - """The error target.""" - details: list["ErrorDetail"] - """The error details.""" - additionalInfo: list["ErrorAdditionalInfo"] - """The error additional info.""" - - -class ErrorResponse(TypedDict, total=False): - """Error response. - - :ivar error: The error object. - :vartype error: ~azure.resourcemanager.multiservicesharedmodels.combined.models.ErrorDetail - """ - - error: "ErrorDetail" - """The error object.""" - - class Resource(TypedDict, total=False): """Resource. @@ -83,8 +27,7 @@ class Resource(TypedDict, total=False): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: - ~azure.resourcemanager.multiservicesharedmodels.combined.models.SystemData + :vartype system_data: "SystemData" """ id: str @@ -103,14 +46,14 @@ class SharedMetadata(TypedDict, total=False): """Common metadata shared across multiple services. :ivar created_at: Creation timestamp of the resource. - :vartype created_at: ~datetime.datetime + :vartype created_at: str :ivar created_by: Creator of the resource. :vartype created_by: str :ivar tags: Tags associated with the resource. :vartype tags: dict[str, str] """ - createdAt: datetime.datetime + createdAt: str """Creation timestamp of the resource.""" createdBy: str """Creator of the resource.""" @@ -131,8 +74,7 @@ class TrackedResource(Resource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: - ~azure.resourcemanager.multiservicesharedmodels.combined.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. @@ -158,15 +100,13 @@ class StorageAccount(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: - ~azure.resourcemanager.multiservicesharedmodels.combined.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: - ~azure.resourcemanager.multiservicesharedmodels.combined.models.StorageAccountProperties + :vartype properties: "StorageAccountProperties" """ properties: "StorageAccountProperties" @@ -177,11 +117,9 @@ class StorageAccountProperties(TypedDict, total=False): """Storage account properties. :ivar provisioning_state: Known values are: "Succeeded", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.resourcemanager.multiservicesharedmodels.combined.models.ResourceProvisioningState + :vartype provisioning_state: Union[str, "ResourceProvisioningState"] :ivar metadata: Shared metadata for the storage account. - :vartype metadata: - ~azure.resourcemanager.multiservicesharedmodels.combined.models.SharedMetadata + :vartype metadata: "SharedMetadata" """ provisioningState: Union[str, "ResourceProvisioningState"] @@ -197,18 +135,16 @@ class SystemData(TypedDict, total=False): :vartype created_by: str :ivar created_by_type: The type of identity that created the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or - ~azure.resourcemanager.multiservicesharedmodels.combined.models.CreatedByType + :vartype created_by_type: Union[str, "CreatedByType"] :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime + :vartype created_at: str :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str :ivar last_modified_by_type: The type of identity that last modified the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or - ~azure.resourcemanager.multiservicesharedmodels.combined.models.CreatedByType + :vartype last_modified_by_type: Union[str, "CreatedByType"] :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime + :vartype last_modified_at: str """ createdBy: str @@ -216,14 +152,14 @@ class SystemData(TypedDict, total=False): createdByType: Union[str, "CreatedByType"] """The type of identity that created the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - createdAt: datetime.datetime + createdAt: str """The timestamp of resource creation (UTC).""" lastModifiedBy: str """The identity that last modified the resource.""" lastModifiedByType: Union[str, "CreatedByType"] """The type of identity that last modified the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - lastModifiedAt: datetime.datetime + lastModifiedAt: str """The timestamp of resource last modification (UTC).""" @@ -240,15 +176,13 @@ class VirtualMachine(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: - ~azure.resourcemanager.multiservicesharedmodels.combined.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: - ~azure.resourcemanager.multiservicesharedmodels.combined.models.VirtualMachineProperties + :vartype properties: "VirtualMachineProperties" """ properties: "VirtualMachineProperties" @@ -259,11 +193,9 @@ class VirtualMachineProperties(TypedDict, total=False): """VirtualMachineProperties. :ivar provisioning_state: Known values are: "Succeeded", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.resourcemanager.multiservicesharedmodels.combined.models.ResourceProvisioningState + :vartype provisioning_state: Union[str, "ResourceProvisioningState"] :ivar metadata: Shared metadata for the virtual machine. - :vartype metadata: - ~azure.resourcemanager.multiservicesharedmodels.combined.models.SharedMetadata + :vartype metadata: "SharedMetadata" """ provisioningState: Union[str, "ResourceProvisioningState"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/pyproject.toml index 270dddee34dc..ab2bf1ab3e5c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service-shared-models/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/operations/_operations.py index 3d6a57262adc..5bac6c39d7c4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/operations/_operations.py @@ -29,7 +29,7 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -40,7 +40,6 @@ ) from .._configuration import CombinedClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -137,7 +136,7 @@ async def _create_or_update_initial( self, resource_group_name: str, vm_name: str, - resource: Union[_models.VirtualMachine, JSON, IO[bytes]], + resource: Union[_models.VirtualMachine, _types.VirtualMachine, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -246,7 +245,7 @@ async def begin_create_or_update( self, resource_group_name: str, vm_name: str, - resource: JSON, + resource: _types.VirtualMachine, *, content_type: str = "application/json", **kwargs: Any @@ -260,7 +259,7 @@ async def begin_create_or_update( :param vm_name: The name of the VirtualMachine. Required. :type vm_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.multiservice.combined.types.VirtualMachine :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -306,7 +305,7 @@ async def begin_create_or_update( self, resource_group_name: str, vm_name: str, - resource: Union[_models.VirtualMachine, JSON, IO[bytes]], + resource: Union[_models.VirtualMachine, _types.VirtualMachine, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.VirtualMachine]: """The operation to create or update a virtual machine. Please note some properties can be set @@ -317,10 +316,10 @@ async def begin_create_or_update( :type resource_group_name: str :param vm_name: The name of the VirtualMachine. Required. :type vm_name: str - :param resource: Resource create parameters. Is one of the following types: VirtualMachine, - JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.multiservice.combined.models.VirtualMachine or JSON or - IO[bytes] + :param resource: Resource create parameters. Is either a VirtualMachine type or a IO[bytes] + type. Required. + :type resource: ~azure.resourcemanager.multiservice.combined.models.VirtualMachine or + ~azure.resourcemanager.multiservice.combined.types.VirtualMachine or IO[bytes] :return: An instance of AsyncLROPoller that returns VirtualMachine. The VirtualMachine is compatible with MutableMapping :rtype: @@ -471,7 +470,11 @@ async def get(self, resource_group_name: str, disk_name: str, **kwargs: Any) -> return deserialized # type: ignore async def _create_or_update_initial( - self, resource_group_name: str, disk_name: str, resource: Union[_models.Disk, JSON, IO[bytes]], **kwargs: Any + self, + resource_group_name: str, + disk_name: str, + resource: Union[_models.Disk, _types.Disk, IO[bytes]], + **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -578,7 +581,7 @@ async def begin_create_or_update( self, resource_group_name: str, disk_name: str, - resource: JSON, + resource: _types.Disk, *, content_type: str = "application/json", **kwargs: Any @@ -591,7 +594,7 @@ async def begin_create_or_update( :param disk_name: The name of the Disk. Required. :type disk_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.multiservice.combined.types.Disk :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -633,7 +636,11 @@ async def begin_create_or_update( @distributed_trace_async async def begin_create_or_update( - self, resource_group_name: str, disk_name: str, resource: Union[_models.Disk, JSON, IO[bytes]], **kwargs: Any + self, + resource_group_name: str, + disk_name: str, + resource: Union[_models.Disk, _types.Disk, IO[bytes]], + **kwargs: Any ) -> AsyncLROPoller[_models.Disk]: """Creates or updates a disk. @@ -642,9 +649,10 @@ async def begin_create_or_update( :type resource_group_name: str :param disk_name: The name of the Disk. Required. :type disk_name: str - :param resource: Resource create parameters. Is one of the following types: Disk, JSON, - IO[bytes] Required. - :type resource: ~azure.resourcemanager.multiservice.combined.models.Disk or JSON or IO[bytes] + :param resource: Resource create parameters. Is either a Disk type or a IO[bytes] type. + Required. + :type resource: ~azure.resourcemanager.multiservice.combined.models.Disk or + ~azure.resourcemanager.multiservice.combined.types.Disk or IO[bytes] :return: An instance of AsyncLROPoller that returns Disk. The Disk is compatible with MutableMapping :rtype: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/operations/_operations.py index 73d530de36af..818332635774 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/operations/_operations.py @@ -30,12 +30,11 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import CombinedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -253,7 +252,7 @@ def _create_or_update_initial( self, resource_group_name: str, vm_name: str, - resource: Union[_models.VirtualMachine, JSON, IO[bytes]], + resource: Union[_models.VirtualMachine, _types.VirtualMachine, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -362,7 +361,7 @@ def begin_create_or_update( self, resource_group_name: str, vm_name: str, - resource: JSON, + resource: _types.VirtualMachine, *, content_type: str = "application/json", **kwargs: Any @@ -376,7 +375,7 @@ def begin_create_or_update( :param vm_name: The name of the VirtualMachine. Required. :type vm_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.multiservice.combined.types.VirtualMachine :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -422,7 +421,7 @@ def begin_create_or_update( self, resource_group_name: str, vm_name: str, - resource: Union[_models.VirtualMachine, JSON, IO[bytes]], + resource: Union[_models.VirtualMachine, _types.VirtualMachine, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.VirtualMachine]: """The operation to create or update a virtual machine. Please note some properties can be set @@ -433,10 +432,10 @@ def begin_create_or_update( :type resource_group_name: str :param vm_name: The name of the VirtualMachine. Required. :type vm_name: str - :param resource: Resource create parameters. Is one of the following types: VirtualMachine, - JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.multiservice.combined.models.VirtualMachine or JSON or - IO[bytes] + :param resource: Resource create parameters. Is either a VirtualMachine type or a IO[bytes] + type. Required. + :type resource: ~azure.resourcemanager.multiservice.combined.models.VirtualMachine or + ~azure.resourcemanager.multiservice.combined.types.VirtualMachine or IO[bytes] :return: An instance of LROPoller that returns VirtualMachine. The VirtualMachine is compatible with MutableMapping :rtype: @@ -587,7 +586,11 @@ def get(self, resource_group_name: str, disk_name: str, **kwargs: Any) -> _model return deserialized # type: ignore def _create_or_update_initial( - self, resource_group_name: str, disk_name: str, resource: Union[_models.Disk, JSON, IO[bytes]], **kwargs: Any + self, + resource_group_name: str, + disk_name: str, + resource: Union[_models.Disk, _types.Disk, IO[bytes]], + **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -692,7 +695,7 @@ def begin_create_or_update( self, resource_group_name: str, disk_name: str, - resource: JSON, + resource: _types.Disk, *, content_type: str = "application/json", **kwargs: Any @@ -705,7 +708,7 @@ def begin_create_or_update( :param disk_name: The name of the Disk. Required. :type disk_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.multiservice.combined.types.Disk :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -743,7 +746,11 @@ def begin_create_or_update( @distributed_trace def begin_create_or_update( - self, resource_group_name: str, disk_name: str, resource: Union[_models.Disk, JSON, IO[bytes]], **kwargs: Any + self, + resource_group_name: str, + disk_name: str, + resource: Union[_models.Disk, _types.Disk, IO[bytes]], + **kwargs: Any ) -> LROPoller[_models.Disk]: """Creates or updates a disk. @@ -752,9 +759,10 @@ def begin_create_or_update( :type resource_group_name: str :param disk_name: The name of the Disk. Required. :type disk_name: str - :param resource: Resource create parameters. Is one of the following types: Disk, JSON, - IO[bytes] Required. - :type resource: ~azure.resourcemanager.multiservice.combined.models.Disk or JSON or IO[bytes] + :param resource: Resource create parameters. Is either a Disk type or a IO[bytes] type. + Required. + :type resource: ~azure.resourcemanager.multiservice.combined.models.Disk or + ~azure.resourcemanager.multiservice.combined.types.Disk or IO[bytes] :return: An instance of LROPoller that returns Disk. The Disk is compatible with MutableMapping :rtype: ~azure.core.polling.LROPoller[~azure.resourcemanager.multiservice.combined.models.Disk] :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/types.py index 4f1670b25dbb..75eaafa3ec8a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/azure/resourcemanager/multiservice/combined/types.py @@ -7,8 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -from typing import Any, TYPE_CHECKING, Union +from typing import TYPE_CHECKING, Union from typing_extensions import Required, TypedDict if TYPE_CHECKING: @@ -28,7 +27,7 @@ class Resource(TypedDict, total=False): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.multiservice.combined.models.SystemData + :vartype system_data: "SystemData" """ id: str @@ -56,7 +55,7 @@ class TrackedResource(Resource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.multiservice.combined.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. @@ -82,13 +81,13 @@ class Disk(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.multiservice.combined.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: ~azure.resourcemanager.multiservice.combined.models.DiskProperties + :vartype properties: "DiskProperties" """ properties: "DiskProperties" @@ -99,68 +98,13 @@ class DiskProperties(TypedDict, total=False): """Disk resource properties. :ivar provisioning_state: Known values are: "Succeeded", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.resourcemanager.multiservice.combined.models.ResourceProvisioningState + :vartype provisioning_state: Union[str, "ResourceProvisioningState"] """ provisioningState: Union[str, "ResourceProvisioningState"] """Known values are: \"Succeeded\", \"Failed\", and \"Canceled\".""" -class ErrorAdditionalInfo(TypedDict, total=False): - """The resource management error additional info. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - type: str - """The additional info type.""" - info: Any - """The additional info.""" - - -class ErrorDetail(TypedDict, total=False): - """The error detail. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.resourcemanager.multiservice.combined.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.resourcemanager.multiservice.combined.models.ErrorAdditionalInfo] - """ - - code: str - """The error code.""" - message: str - """The error message.""" - target: str - """The error target.""" - details: list["ErrorDetail"] - """The error details.""" - additionalInfo: list["ErrorAdditionalInfo"] - """The error additional info.""" - - -class ErrorResponse(TypedDict, total=False): - """Error response. - - :ivar error: The error object. - :vartype error: ~azure.resourcemanager.multiservice.combined.models.ErrorDetail - """ - - error: "ErrorDetail" - """The error object.""" - - class SystemData(TypedDict, total=False): """Metadata pertaining to creation and last modification of the resource. @@ -168,18 +112,16 @@ class SystemData(TypedDict, total=False): :vartype created_by: str :ivar created_by_type: The type of identity that created the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or - ~azure.resourcemanager.multiservice.combined.models.CreatedByType + :vartype created_by_type: Union[str, "CreatedByType"] :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime + :vartype created_at: str :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str :ivar last_modified_by_type: The type of identity that last modified the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or - ~azure.resourcemanager.multiservice.combined.models.CreatedByType + :vartype last_modified_by_type: Union[str, "CreatedByType"] :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime + :vartype last_modified_at: str """ createdBy: str @@ -187,14 +129,14 @@ class SystemData(TypedDict, total=False): createdByType: Union[str, "CreatedByType"] """The type of identity that created the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - createdAt: datetime.datetime + createdAt: str """The timestamp of resource creation (UTC).""" lastModifiedBy: str """The identity that last modified the resource.""" lastModifiedByType: Union[str, "CreatedByType"] """The type of identity that last modified the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - lastModifiedAt: datetime.datetime + lastModifiedAt: str """The timestamp of resource last modification (UTC).""" @@ -211,14 +153,13 @@ class VirtualMachine(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.multiservice.combined.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: - ~azure.resourcemanager.multiservice.combined.models.VirtualMachineProperties + :vartype properties: "VirtualMachineProperties" """ properties: "VirtualMachineProperties" @@ -229,8 +170,7 @@ class VirtualMachineProperties(TypedDict, total=False): """VirtualMachineProperties. :ivar provisioning_state: Known values are: "Succeeded", "Failed", and "Canceled". - :vartype provisioning_state: str or - ~azure.resourcemanager.multiservice.combined.models.ResourceProvisioningState + :vartype provisioning_state: Union[str, "ResourceProvisioningState"] """ provisioningState: Union[str, "ResourceProvisioningState"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/pyproject.toml index 286dc4586899..fa1cb73fe15f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-multi-service/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/operations/_operations.py index 818e234f10c8..ba9fb8c5f849 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -36,7 +36,6 @@ ) from .._configuration import NonResourceClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -155,7 +154,13 @@ async def create( @overload async def create( - self, location: str, parameter: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + location: str, + parameter: str, + body: _types.NonResource, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.NonResource: """create. @@ -164,7 +169,7 @@ async def create( :param parameter: Another parameter. Required. :type parameter: str :param body: The request body. Required. - :type body: JSON + :type body: ~azure.resourcemanager.nonresource.types.NonResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -195,7 +200,11 @@ async def create( @distributed_trace_async async def create( - self, location: str, parameter: str, body: Union[_models.NonResource, JSON, IO[bytes]], **kwargs: Any + self, + location: str, + parameter: str, + body: Union[_models.NonResource, _types.NonResource, IO[bytes]], + **kwargs: Any ) -> _models.NonResource: """create. @@ -203,9 +212,9 @@ async def create( :type location: str :param parameter: Another parameter. Required. :type parameter: str - :param body: The request body. Is one of the following types: NonResource, JSON, IO[bytes] - Required. - :type body: ~azure.resourcemanager.nonresource.models.NonResource or JSON or IO[bytes] + :param body: The request body. Is either a NonResource type or a IO[bytes] type. Required. + :type body: ~azure.resourcemanager.nonresource.models.NonResource or + ~azure.resourcemanager.nonresource.types.NonResource or IO[bytes] :return: NonResource. The NonResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.nonresource.models.NonResource :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/operations/_operations.py index c1e72d85a448..1ea579b46c26 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/operations/_operations.py @@ -28,12 +28,11 @@ from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import NonResourceClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -214,7 +213,13 @@ def create( @overload def create( - self, location: str, parameter: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + location: str, + parameter: str, + body: _types.NonResource, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.NonResource: """create. @@ -223,7 +228,7 @@ def create( :param parameter: Another parameter. Required. :type parameter: str :param body: The request body. Required. - :type body: JSON + :type body: ~azure.resourcemanager.nonresource.types.NonResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -254,7 +259,11 @@ def create( @distributed_trace def create( - self, location: str, parameter: str, body: Union[_models.NonResource, JSON, IO[bytes]], **kwargs: Any + self, + location: str, + parameter: str, + body: Union[_models.NonResource, _types.NonResource, IO[bytes]], + **kwargs: Any ) -> _models.NonResource: """create. @@ -262,9 +271,9 @@ def create( :type location: str :param parameter: Another parameter. Required. :type parameter: str - :param body: The request body. Is one of the following types: NonResource, JSON, IO[bytes] - Required. - :type body: ~azure.resourcemanager.nonresource.models.NonResource or JSON or IO[bytes] + :param body: The request body. Is either a NonResource type or a IO[bytes] type. Required. + :type body: ~azure.resourcemanager.nonresource.models.NonResource or + ~azure.resourcemanager.nonresource.types.NonResource or IO[bytes] :return: NonResource. The NonResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.nonresource.models.NonResource :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/types.py index fa7328667dc4..271a06d17b83 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/azure/resourcemanager/nonresource/types.py @@ -6,63 +6,9 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any from typing_extensions import TypedDict -class ErrorAdditionalInfo(TypedDict, total=False): - """The resource management error additional info. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - type: str - """The additional info type.""" - info: Any - """The additional info.""" - - -class ErrorDetail(TypedDict, total=False): - """The error detail. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.resourcemanager.nonresource.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.resourcemanager.nonresource.models.ErrorAdditionalInfo] - """ - - code: str - """The error code.""" - message: str - """The error message.""" - target: str - """The error target.""" - details: list["ErrorDetail"] - """The error details.""" - additionalInfo: list["ErrorAdditionalInfo"] - """The error additional info.""" - - -class ErrorResponse(TypedDict, total=False): - """Error response. - - :ivar error: The error object. - :vartype error: ~azure.resourcemanager.nonresource.models.ErrorDetail - """ - - error: "ErrorDetail" - """The error object.""" - - class NonResource(TypedDict, total=False): """Though this model has ``id``, ``name``, ``type`` properties, it is not a resource as it doesn't extends ``Resource``. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/pyproject.toml index 20d31b791672..b3cdc135df05 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-non-resource/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/operations/_operations.py index 47f2d2f54728..f3059d07f5b7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/operations/_operations.py @@ -33,7 +33,7 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -54,7 +54,6 @@ T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] List = list @@ -205,12 +204,12 @@ async def check_global( @overload async def check_global( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.CheckNameAvailabilityRequest, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Implements global CheckNameAvailability operations. :param body: The CheckAvailability request. Required. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.CheckNameAvailabilityRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -239,14 +238,16 @@ async def check_global( @distributed_trace_async async def check_global( - self, body: Union[_models.CheckNameAvailabilityRequest, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.CheckNameAvailabilityRequest, _types.CheckNameAvailabilityRequest, IO[bytes]], + **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Implements global CheckNameAvailability operations. - :param body: The CheckAvailability request. Is one of the following types: - CheckNameAvailabilityRequest, JSON, IO[bytes] Required. + :param body: The CheckAvailability request. Is either a CheckNameAvailabilityRequest type or a + IO[bytes] type. Required. :type body: ~azure.resourcemanager.operationtemplates.models.CheckNameAvailabilityRequest or - JSON or IO[bytes] + ~azure.resourcemanager.operationtemplates.types.CheckNameAvailabilityRequest or IO[bytes] :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with MutableMapping :rtype: ~azure.resourcemanager.operationtemplates.models.CheckNameAvailabilityResponse @@ -343,14 +344,19 @@ async def check_local( @overload async def check_local( - self, location: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + location: str, + body: _types.CheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Implements local CheckNameAvailability operations. :param location: The name of the Azure region. Required. :type location: str :param body: The CheckAvailability request. Required. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.CheckNameAvailabilityRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -381,16 +387,19 @@ async def check_local( @distributed_trace_async async def check_local( - self, location: str, body: Union[_models.CheckNameAvailabilityRequest, JSON, IO[bytes]], **kwargs: Any + self, + location: str, + body: Union[_models.CheckNameAvailabilityRequest, _types.CheckNameAvailabilityRequest, IO[bytes]], + **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Implements local CheckNameAvailability operations. :param location: The name of the Azure region. Required. :type location: str - :param body: The CheckAvailability request. Is one of the following types: - CheckNameAvailabilityRequest, JSON, IO[bytes] Required. + :param body: The CheckAvailability request. Is either a CheckNameAvailabilityRequest type or a + IO[bytes] type. Required. :type body: ~azure.resourcemanager.operationtemplates.models.CheckNameAvailabilityRequest or - JSON or IO[bytes] + ~azure.resourcemanager.operationtemplates.types.CheckNameAvailabilityRequest or IO[bytes] :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with MutableMapping :rtype: ~azure.resourcemanager.operationtemplates.models.CheckNameAvailabilityResponse @@ -481,7 +490,11 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") async def _create_or_replace_initial( - self, resource_group_name: str, order_name: str, resource: Union[_models.Order, JSON, IO[bytes]], **kwargs: Any + self, + resource_group_name: str, + order_name: str, + resource: Union[_models.Order, _types.Order, IO[bytes]], + **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -587,7 +600,7 @@ async def begin_create_or_replace( self, resource_group_name: str, order_name: str, - resource: JSON, + resource: _types.Order, *, content_type: str = "application/json", **kwargs: Any @@ -600,7 +613,7 @@ async def begin_create_or_replace( :param order_name: The name of the Order. Required. :type order_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.operationtemplates.types.Order :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -642,7 +655,11 @@ async def begin_create_or_replace( @distributed_trace_async async def begin_create_or_replace( - self, resource_group_name: str, order_name: str, resource: Union[_models.Order, JSON, IO[bytes]], **kwargs: Any + self, + resource_group_name: str, + order_name: str, + resource: Union[_models.Order, _types.Order, IO[bytes]], + **kwargs: Any ) -> AsyncLROPoller[_models.Order]: """Create a Order. @@ -651,9 +668,10 @@ async def begin_create_or_replace( :type resource_group_name: str :param order_name: The name of the Order. Required. :type order_name: str - :param resource: Resource create parameters. Is one of the following types: Order, JSON, - IO[bytes] Required. - :type resource: ~azure.resourcemanager.operationtemplates.models.Order or JSON or IO[bytes] + :param resource: Resource create parameters. Is either a Order type or a IO[bytes] type. + Required. + :type resource: ~azure.resourcemanager.operationtemplates.models.Order or + ~azure.resourcemanager.operationtemplates.types.Order or IO[bytes] :return: An instance of AsyncLROPoller that returns Order. The Order is compatible with MutableMapping :rtype: @@ -716,7 +734,7 @@ async def _export_initial( self, resource_group_name: str, order_name: str, - body: Union[_models.ExportRequest, JSON, IO[bytes]], + body: Union[_models.ExportRequest, _types.ExportRequest, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -800,7 +818,7 @@ async def begin_export( content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.ExportResult]: - """A long-running resource action. + """export. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. @@ -824,12 +842,12 @@ async def begin_export( self, resource_group_name: str, order_name: str, - body: JSON, + body: _types.ExportRequest, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.ExportResult]: - """A long-running resource action. + """export. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. @@ -837,7 +855,7 @@ async def begin_export( :param order_name: The name of the Order. Required. :type order_name: str :param body: The content of the action request. Required. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.ExportRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -858,7 +876,7 @@ async def begin_export( content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.ExportResult]: - """A long-running resource action. + """export. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. @@ -882,19 +900,20 @@ async def begin_export( self, resource_group_name: str, order_name: str, - body: Union[_models.ExportRequest, JSON, IO[bytes]], + body: Union[_models.ExportRequest, _types.ExportRequest, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.ExportResult]: - """A long-running resource action. + """export. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str :param order_name: The name of the Order. Required. :type order_name: str - :param body: The content of the action request. Is one of the following types: ExportRequest, - JSON, IO[bytes] Required. - :type body: ~azure.resourcemanager.operationtemplates.models.ExportRequest or JSON or IO[bytes] + :param body: The content of the action request. Is either a ExportRequest type or a IO[bytes] + type. Required. + :type body: ~azure.resourcemanager.operationtemplates.models.ExportRequest or + ~azure.resourcemanager.operationtemplates.types.ExportRequest or IO[bytes] :return: An instance of AsyncLROPoller that returns ExportResult. The ExportResult is compatible with MutableMapping :rtype: @@ -1070,7 +1089,7 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore async def _export_array_initial( - self, body: Union[_models.ExportRequest, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ExportRequest, _types.ExportRequest, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -1160,12 +1179,12 @@ async def begin_export_array( @overload async def begin_export_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ExportRequest, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[List[_models.ExportResult]]: """export_array. :param body: The request body. Required. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.ExportRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1194,13 +1213,13 @@ async def begin_export_array( @distributed_trace_async async def begin_export_array( - self, body: Union[_models.ExportRequest, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ExportRequest, _types.ExportRequest, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[List[_models.ExportResult]]: """export_array. - :param body: The request body. Is one of the following types: ExportRequest, JSON, IO[bytes] - Required. - :type body: ~azure.resourcemanager.operationtemplates.models.ExportRequest or JSON or IO[bytes] + :param body: The request body. Is either a ExportRequest type or a IO[bytes] type. Required. + :type body: ~azure.resourcemanager.operationtemplates.models.ExportRequest or + ~azure.resourcemanager.operationtemplates.types.ExportRequest or IO[bytes] :return: An instance of AsyncLROPoller that returns list of ExportResult :rtype: ~azure.core.polling.AsyncLROPoller[list[~azure.resourcemanager.operationtemplates.models.ExportResult]] @@ -1334,7 +1353,7 @@ async def _post_paging_lro_initial( async def begin_post_paging_lro( self, resource_group_name: str, product_name: str, **kwargs: Any ) -> AsyncLROPoller[AsyncItemPaged["_models.Product"]]: - """A long-running resource action. + """post_paging_lro. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. @@ -1598,7 +1617,7 @@ async def patch( self, resource_group_name: str, widget_name: str, - properties: Optional[JSON] = None, + properties: Optional[_types.Widget] = None, *, content_type: str = "application/json", **kwargs: Any @@ -1611,7 +1630,7 @@ async def patch( :param widget_name: The name of the Widget. Required. :type widget_name: str :param properties: The resource properties to be updated. Default value is None. - :type properties: JSON + :type properties: ~azure.resourcemanager.operationtemplates.types.Widget :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1652,7 +1671,7 @@ async def patch( self, resource_group_name: str, widget_name: str, - properties: Optional[Union[_models.Widget, JSON, IO[bytes]]] = None, + properties: Optional[Union[_models.Widget, _types.Widget, IO[bytes]]] = None, **kwargs: Any ) -> _models.Widget: """Update a Widget. @@ -1662,9 +1681,10 @@ async def patch( :type resource_group_name: str :param widget_name: The name of the Widget. Required. :type widget_name: str - :param properties: The resource properties to be updated. Is one of the following types: - Widget, JSON, IO[bytes] Default value is None. - :type properties: ~azure.resourcemanager.operationtemplates.models.Widget or JSON or IO[bytes] + :param properties: The resource properties to be updated. Is either a Widget type or a + IO[bytes] type. Default value is None. + :type properties: ~azure.resourcemanager.operationtemplates.models.Widget or + ~azure.resourcemanager.operationtemplates.types.Widget or IO[bytes] :return: Widget. The Widget is compatible with MutableMapping :rtype: ~azure.resourcemanager.operationtemplates.models.Widget :raises ~azure.core.exceptions.HttpResponseError: @@ -1772,7 +1792,7 @@ async def post( self, resource_group_name: str, widget_name: str, - body: Optional[JSON] = None, + body: Optional[_types.ActionRequest] = None, *, content_type: str = "application/json", **kwargs: Any @@ -1785,7 +1805,7 @@ async def post( :param widget_name: The name of the Widget. Required. :type widget_name: str :param body: The content of the action request. Default value is None. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.ActionRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1826,7 +1846,7 @@ async def post( self, resource_group_name: str, widget_name: str, - body: Optional[Union[_models.ActionRequest, JSON, IO[bytes]]] = None, + body: Optional[Union[_models.ActionRequest, _types.ActionRequest, IO[bytes]]] = None, **kwargs: Any ) -> _models.ActionResult: """A synchronous resource action. @@ -1836,9 +1856,10 @@ async def post( :type resource_group_name: str :param widget_name: The name of the Widget. Required. :type widget_name: str - :param body: The content of the action request. Is one of the following types: ActionRequest, - JSON, IO[bytes] Default value is None. - :type body: ~azure.resourcemanager.operationtemplates.models.ActionRequest or JSON or IO[bytes] + :param body: The content of the action request. Is either a ActionRequest type or a IO[bytes] + type. Default value is None. + :type body: ~azure.resourcemanager.operationtemplates.models.ActionRequest or + ~azure.resourcemanager.operationtemplates.types.ActionRequest or IO[bytes] :return: ActionResult. The ActionResult is compatible with MutableMapping :rtype: ~azure.resourcemanager.operationtemplates.models.ActionResult :raises ~azure.core.exceptions.HttpResponseError: @@ -1936,12 +1957,16 @@ async def provider_post( @overload async def provider_post( - self, body: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any + self, + body: Optional[_types.ChangeAllowanceRequest] = None, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.ChangeAllowanceResult: """provider_post. :param body: The request body. Default value is None. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.ChangeAllowanceRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1968,14 +1993,16 @@ async def provider_post( @distributed_trace_async async def provider_post( - self, body: Optional[Union[_models.ChangeAllowanceRequest, JSON, IO[bytes]]] = None, **kwargs: Any + self, + body: Optional[Union[_models.ChangeAllowanceRequest, _types.ChangeAllowanceRequest, IO[bytes]]] = None, + **kwargs: Any ) -> _models.ChangeAllowanceResult: """provider_post. - :param body: The request body. Is one of the following types: ChangeAllowanceRequest, JSON, - IO[bytes] Default value is None. - :type body: ~azure.resourcemanager.operationtemplates.models.ChangeAllowanceRequest or JSON or - IO[bytes] + :param body: The request body. Is either a ChangeAllowanceRequest type or a IO[bytes] type. + Default value is None. + :type body: ~azure.resourcemanager.operationtemplates.models.ChangeAllowanceRequest or + ~azure.resourcemanager.operationtemplates.types.ChangeAllowanceRequest or IO[bytes] :return: ChangeAllowanceResult. The ChangeAllowanceResult is compatible with MutableMapping :rtype: ~azure.resourcemanager.operationtemplates.models.ChangeAllowanceResult :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/operations/_operations.py index 19adb4c5f86b..09742a806b76 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/operations/_operations.py @@ -32,14 +32,13 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import OperationTemplatesClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from .._utils.serialization import Deserializer, Serializer T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] List = list _SERIALIZER = Serializer() @@ -529,12 +528,12 @@ def check_global( @overload def check_global( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.CheckNameAvailabilityRequest, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Implements global CheckNameAvailability operations. :param body: The CheckAvailability request. Required. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.CheckNameAvailabilityRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -563,14 +562,16 @@ def check_global( @distributed_trace def check_global( - self, body: Union[_models.CheckNameAvailabilityRequest, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.CheckNameAvailabilityRequest, _types.CheckNameAvailabilityRequest, IO[bytes]], + **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Implements global CheckNameAvailability operations. - :param body: The CheckAvailability request. Is one of the following types: - CheckNameAvailabilityRequest, JSON, IO[bytes] Required. + :param body: The CheckAvailability request. Is either a CheckNameAvailabilityRequest type or a + IO[bytes] type. Required. :type body: ~azure.resourcemanager.operationtemplates.models.CheckNameAvailabilityRequest or - JSON or IO[bytes] + ~azure.resourcemanager.operationtemplates.types.CheckNameAvailabilityRequest or IO[bytes] :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with MutableMapping :rtype: ~azure.resourcemanager.operationtemplates.models.CheckNameAvailabilityResponse @@ -667,14 +668,19 @@ def check_local( @overload def check_local( - self, location: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + location: str, + body: _types.CheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Implements local CheckNameAvailability operations. :param location: The name of the Azure region. Required. :type location: str :param body: The CheckAvailability request. Required. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.CheckNameAvailabilityRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -705,16 +711,19 @@ def check_local( @distributed_trace def check_local( - self, location: str, body: Union[_models.CheckNameAvailabilityRequest, JSON, IO[bytes]], **kwargs: Any + self, + location: str, + body: Union[_models.CheckNameAvailabilityRequest, _types.CheckNameAvailabilityRequest, IO[bytes]], + **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Implements local CheckNameAvailability operations. :param location: The name of the Azure region. Required. :type location: str - :param body: The CheckAvailability request. Is one of the following types: - CheckNameAvailabilityRequest, JSON, IO[bytes] Required. + :param body: The CheckAvailability request. Is either a CheckNameAvailabilityRequest type or a + IO[bytes] type. Required. :type body: ~azure.resourcemanager.operationtemplates.models.CheckNameAvailabilityRequest or - JSON or IO[bytes] + ~azure.resourcemanager.operationtemplates.types.CheckNameAvailabilityRequest or IO[bytes] :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with MutableMapping :rtype: ~azure.resourcemanager.operationtemplates.models.CheckNameAvailabilityResponse @@ -805,7 +814,11 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") def _create_or_replace_initial( - self, resource_group_name: str, order_name: str, resource: Union[_models.Order, JSON, IO[bytes]], **kwargs: Any + self, + resource_group_name: str, + order_name: str, + resource: Union[_models.Order, _types.Order, IO[bytes]], + **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -910,7 +923,7 @@ def begin_create_or_replace( self, resource_group_name: str, order_name: str, - resource: JSON, + resource: _types.Order, *, content_type: str = "application/json", **kwargs: Any @@ -923,7 +936,7 @@ def begin_create_or_replace( :param order_name: The name of the Order. Required. :type order_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.operationtemplates.types.Order :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -963,7 +976,11 @@ def begin_create_or_replace( @distributed_trace def begin_create_or_replace( - self, resource_group_name: str, order_name: str, resource: Union[_models.Order, JSON, IO[bytes]], **kwargs: Any + self, + resource_group_name: str, + order_name: str, + resource: Union[_models.Order, _types.Order, IO[bytes]], + **kwargs: Any ) -> LROPoller[_models.Order]: """Create a Order. @@ -972,9 +989,10 @@ def begin_create_or_replace( :type resource_group_name: str :param order_name: The name of the Order. Required. :type order_name: str - :param resource: Resource create parameters. Is one of the following types: Order, JSON, - IO[bytes] Required. - :type resource: ~azure.resourcemanager.operationtemplates.models.Order or JSON or IO[bytes] + :param resource: Resource create parameters. Is either a Order type or a IO[bytes] type. + Required. + :type resource: ~azure.resourcemanager.operationtemplates.models.Order or + ~azure.resourcemanager.operationtemplates.types.Order or IO[bytes] :return: An instance of LROPoller that returns Order. The Order is compatible with MutableMapping :rtype: ~azure.core.polling.LROPoller[~azure.resourcemanager.operationtemplates.models.Order] @@ -1036,7 +1054,7 @@ def _export_initial( self, resource_group_name: str, order_name: str, - body: Union[_models.ExportRequest, JSON, IO[bytes]], + body: Union[_models.ExportRequest, _types.ExportRequest, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -1120,7 +1138,7 @@ def begin_export( content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.ExportResult]: - """A long-running resource action. + """export. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. @@ -1144,12 +1162,12 @@ def begin_export( self, resource_group_name: str, order_name: str, - body: JSON, + body: _types.ExportRequest, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.ExportResult]: - """A long-running resource action. + """export. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. @@ -1157,7 +1175,7 @@ def begin_export( :param order_name: The name of the Order. Required. :type order_name: str :param body: The content of the action request. Required. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.ExportRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1178,7 +1196,7 @@ def begin_export( content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.ExportResult]: - """A long-running resource action. + """export. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. @@ -1202,19 +1220,20 @@ def begin_export( self, resource_group_name: str, order_name: str, - body: Union[_models.ExportRequest, JSON, IO[bytes]], + body: Union[_models.ExportRequest, _types.ExportRequest, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.ExportResult]: - """A long-running resource action. + """export. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str :param order_name: The name of the Order. Required. :type order_name: str - :param body: The content of the action request. Is one of the following types: ExportRequest, - JSON, IO[bytes] Required. - :type body: ~azure.resourcemanager.operationtemplates.models.ExportRequest or JSON or IO[bytes] + :param body: The content of the action request. Is either a ExportRequest type or a IO[bytes] + type. Required. + :type body: ~azure.resourcemanager.operationtemplates.models.ExportRequest or + ~azure.resourcemanager.operationtemplates.types.ExportRequest or IO[bytes] :return: An instance of LROPoller that returns ExportResult. The ExportResult is compatible with MutableMapping :rtype: @@ -1390,7 +1409,7 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore def _export_array_initial( - self, body: Union[_models.ExportRequest, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ExportRequest, _types.ExportRequest, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -1480,12 +1499,12 @@ def begin_export_array( @overload def begin_export_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ExportRequest, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[List[_models.ExportResult]]: """export_array. :param body: The request body. Required. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.ExportRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1514,13 +1533,13 @@ def begin_export_array( @distributed_trace def begin_export_array( - self, body: Union[_models.ExportRequest, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ExportRequest, _types.ExportRequest, IO[bytes]], **kwargs: Any ) -> LROPoller[List[_models.ExportResult]]: """export_array. - :param body: The request body. Is one of the following types: ExportRequest, JSON, IO[bytes] - Required. - :type body: ~azure.resourcemanager.operationtemplates.models.ExportRequest or JSON or IO[bytes] + :param body: The request body. Is either a ExportRequest type or a IO[bytes] type. Required. + :type body: ~azure.resourcemanager.operationtemplates.models.ExportRequest or + ~azure.resourcemanager.operationtemplates.types.ExportRequest or IO[bytes] :return: An instance of LROPoller that returns list of ExportResult :rtype: ~azure.core.polling.LROPoller[list[~azure.resourcemanager.operationtemplates.models.ExportResult]] @@ -1652,7 +1671,7 @@ def _post_paging_lro_initial(self, resource_group_name: str, product_name: str, def begin_post_paging_lro( self, resource_group_name: str, product_name: str, **kwargs: Any ) -> LROPoller[ItemPaged["_models.Product"]]: - """A long-running resource action. + """post_paging_lro. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. @@ -1916,7 +1935,7 @@ def patch( self, resource_group_name: str, widget_name: str, - properties: Optional[JSON] = None, + properties: Optional[_types.Widget] = None, *, content_type: str = "application/json", **kwargs: Any @@ -1929,7 +1948,7 @@ def patch( :param widget_name: The name of the Widget. Required. :type widget_name: str :param properties: The resource properties to be updated. Default value is None. - :type properties: JSON + :type properties: ~azure.resourcemanager.operationtemplates.types.Widget :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1970,7 +1989,7 @@ def patch( self, resource_group_name: str, widget_name: str, - properties: Optional[Union[_models.Widget, JSON, IO[bytes]]] = None, + properties: Optional[Union[_models.Widget, _types.Widget, IO[bytes]]] = None, **kwargs: Any ) -> _models.Widget: """Update a Widget. @@ -1980,9 +1999,10 @@ def patch( :type resource_group_name: str :param widget_name: The name of the Widget. Required. :type widget_name: str - :param properties: The resource properties to be updated. Is one of the following types: - Widget, JSON, IO[bytes] Default value is None. - :type properties: ~azure.resourcemanager.operationtemplates.models.Widget or JSON or IO[bytes] + :param properties: The resource properties to be updated. Is either a Widget type or a + IO[bytes] type. Default value is None. + :type properties: ~azure.resourcemanager.operationtemplates.models.Widget or + ~azure.resourcemanager.operationtemplates.types.Widget or IO[bytes] :return: Widget. The Widget is compatible with MutableMapping :rtype: ~azure.resourcemanager.operationtemplates.models.Widget :raises ~azure.core.exceptions.HttpResponseError: @@ -2090,7 +2110,7 @@ def post( self, resource_group_name: str, widget_name: str, - body: Optional[JSON] = None, + body: Optional[_types.ActionRequest] = None, *, content_type: str = "application/json", **kwargs: Any @@ -2103,7 +2123,7 @@ def post( :param widget_name: The name of the Widget. Required. :type widget_name: str :param body: The content of the action request. Default value is None. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.ActionRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2144,7 +2164,7 @@ def post( self, resource_group_name: str, widget_name: str, - body: Optional[Union[_models.ActionRequest, JSON, IO[bytes]]] = None, + body: Optional[Union[_models.ActionRequest, _types.ActionRequest, IO[bytes]]] = None, **kwargs: Any ) -> _models.ActionResult: """A synchronous resource action. @@ -2154,9 +2174,10 @@ def post( :type resource_group_name: str :param widget_name: The name of the Widget. Required. :type widget_name: str - :param body: The content of the action request. Is one of the following types: ActionRequest, - JSON, IO[bytes] Default value is None. - :type body: ~azure.resourcemanager.operationtemplates.models.ActionRequest or JSON or IO[bytes] + :param body: The content of the action request. Is either a ActionRequest type or a IO[bytes] + type. Default value is None. + :type body: ~azure.resourcemanager.operationtemplates.models.ActionRequest or + ~azure.resourcemanager.operationtemplates.types.ActionRequest or IO[bytes] :return: ActionResult. The ActionResult is compatible with MutableMapping :rtype: ~azure.resourcemanager.operationtemplates.models.ActionResult :raises ~azure.core.exceptions.HttpResponseError: @@ -2254,12 +2275,16 @@ def provider_post( @overload def provider_post( - self, body: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any + self, + body: Optional[_types.ChangeAllowanceRequest] = None, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.ChangeAllowanceResult: """provider_post. :param body: The request body. Default value is None. - :type body: JSON + :type body: ~azure.resourcemanager.operationtemplates.types.ChangeAllowanceRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2286,14 +2311,16 @@ def provider_post( @distributed_trace def provider_post( - self, body: Optional[Union[_models.ChangeAllowanceRequest, JSON, IO[bytes]]] = None, **kwargs: Any + self, + body: Optional[Union[_models.ChangeAllowanceRequest, _types.ChangeAllowanceRequest, IO[bytes]]] = None, + **kwargs: Any ) -> _models.ChangeAllowanceResult: """provider_post. - :param body: The request body. Is one of the following types: ChangeAllowanceRequest, JSON, - IO[bytes] Default value is None. - :type body: ~azure.resourcemanager.operationtemplates.models.ChangeAllowanceRequest or JSON or - IO[bytes] + :param body: The request body. Is either a ChangeAllowanceRequest type or a IO[bytes] type. + Default value is None. + :type body: ~azure.resourcemanager.operationtemplates.models.ChangeAllowanceRequest or + ~azure.resourcemanager.operationtemplates.types.ChangeAllowanceRequest or IO[bytes] :return: ChangeAllowanceResult. The ChangeAllowanceResult is compatible with MutableMapping :rtype: ~azure.resourcemanager.operationtemplates.models.ChangeAllowanceResult :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/types.py index 8dd0cca86f50..88067776a6ee 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/azure/resourcemanager/operationtemplates/types.py @@ -7,12 +7,11 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -from typing import Any, TYPE_CHECKING, Union +from typing import TYPE_CHECKING, Union from typing_extensions import Required, TypedDict if TYPE_CHECKING: - from .models import ActionType, CheckNameAvailabilityReason, CreatedByType, Origin + from .models import CreatedByType class ActionRequest(TypedDict, total=False): @@ -30,17 +29,6 @@ class ActionRequest(TypedDict, total=False): """Additional action parameters.""" -class ActionResult(TypedDict, total=False): - """ActionResult. - - :ivar result: The result of the action. Required. - :vartype result: str - """ - - result: Required[str] - """The result of the action. Required.""" - - class ChangeAllowanceRequest(TypedDict, total=False): """ChangeAllowanceRequest. @@ -56,21 +44,6 @@ class ChangeAllowanceRequest(TypedDict, total=False): """The reason for the change.""" -class ChangeAllowanceResult(TypedDict, total=False): - """ChangeAllowanceResult. - - :ivar total_allowed: The new total allowed widgets. Required. - :vartype total_allowed: int - :ivar status: The status of the change. Required. - :vartype status: str - """ - - totalAllowed: Required[int] - """The new total allowed widgets. Required.""" - status: Required[str] - """The status of the change. Required.""" - - class CheckNameAvailabilityRequest(TypedDict, total=False): """The check availability request body. @@ -86,82 +59,6 @@ class CheckNameAvailabilityRequest(TypedDict, total=False): """The resource type.""" -class CheckNameAvailabilityResponse(TypedDict, total=False): - """The check availability result. - - :ivar name_available: Indicates if the resource name is available. - :vartype name_available: bool - :ivar reason: The reason why the given name is not available. Known values are: "Invalid" and - "AlreadyExists". - :vartype reason: str or - ~azure.resourcemanager.operationtemplates.models.CheckNameAvailabilityReason - :ivar message: Detailed reason why the given name is not available. - :vartype message: str - """ - - nameAvailable: bool - """Indicates if the resource name is available.""" - reason: Union[str, "CheckNameAvailabilityReason"] - """The reason why the given name is not available. Known values are: \"Invalid\" and - \"AlreadyExists\".""" - message: str - """Detailed reason why the given name is not available.""" - - -class ErrorAdditionalInfo(TypedDict, total=False): - """The resource management error additional info. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - type: str - """The additional info type.""" - info: Any - """The additional info.""" - - -class ErrorDetail(TypedDict, total=False): - """The error detail. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.resourcemanager.operationtemplates.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.resourcemanager.operationtemplates.models.ErrorAdditionalInfo] - """ - - code: str - """The error code.""" - message: str - """The error message.""" - target: str - """The error target.""" - details: list["ErrorDetail"] - """The error details.""" - additionalInfo: list["ErrorAdditionalInfo"] - """The error additional info.""" - - -class ErrorResponse(TypedDict, total=False): - """Error response. - - :ivar error: The error object. - :vartype error: ~azure.resourcemanager.operationtemplates.models.ErrorDetail - """ - - error: "ErrorDetail" - """The error object.""" - - class ExportRequest(TypedDict, total=False): """ExportRequest. @@ -173,86 +70,6 @@ class ExportRequest(TypedDict, total=False): """Format of the exported order. Required.""" -class ExportResult(TypedDict, total=False): - """ExportResult. - - :ivar content: Content of the exported order. Required. - :vartype content: str - """ - - content: Required[str] - """Content of the exported order. Required.""" - - -class Operation(TypedDict, total=False): - """REST API Operation. - - :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: - "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". - :vartype name: str - :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for - data-plane operations and "false" for Azure Resource Manager/control-plane operations. - :vartype is_data_action: bool - :ivar display: Localized display information for this particular operation. - :vartype display: ~azure.resourcemanager.operationtemplates.models.OperationDisplay - :ivar origin: The intended executor of the operation; as in Resource Based Access Control - (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", - and "user,system". - :vartype origin: str or ~azure.resourcemanager.operationtemplates.models.Origin - :ivar action_type: Extensible enum. Indicates the action type. "Internal" refers to actions - that are for internal only APIs. "Internal" - :vartype action_type: str or ~azure.resourcemanager.operationtemplates.models.ActionType - """ - - name: str - """The name of the operation, as per Resource-Based Access Control (RBAC). Examples: - \"Microsoft.Compute/virtualMachines/write\", - \"Microsoft.Compute/virtualMachines/capture/action\".""" - isDataAction: bool - """Whether the operation applies to data-plane. This is \"true\" for data-plane operations and - \"false\" for Azure Resource Manager/control-plane operations.""" - display: "OperationDisplay" - """Localized display information for this particular operation.""" - origin: Union[str, "Origin"] - """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit - logs UX. Default value is \"user,system\". Known values are: \"user\", \"system\", and - \"user,system\".""" - actionType: Union[str, "ActionType"] - """Extensible enum. Indicates the action type. \"Internal\" refers to actions that are for - internal only APIs. \"Internal\"""" - - -class OperationDisplay(TypedDict, total=False): - """Localized display information for an operation. - - :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft - Monitoring Insights" or "Microsoft Compute". - :vartype provider: str - :ivar resource: The localized friendly name of the resource type related to this operation. - E.g. "Virtual Machines" or "Job Schedule Collections". - :vartype resource: str - :ivar operation: The concise, localized friendly name for the operation; suitable for - dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". - :vartype operation: str - :ivar description: The short, localized friendly description of the operation; suitable for - tool tips and detailed views. - :vartype description: str - """ - - provider: str - """The localized friendly form of the resource provider name, e.g. \"Microsoft Monitoring - Insights\" or \"Microsoft Compute\".""" - resource: str - """The localized friendly name of the resource type related to this operation. E.g. \"Virtual - Machines\" or \"Job Schedule Collections\".""" - operation: str - """The concise, localized friendly name for the operation; suitable for dropdowns. E.g. \"Create - or Update Virtual Machine\", \"Restart Virtual Machine\".""" - description: str - """The short, localized friendly description of the operation; suitable for tool tips and detailed - views.""" - - class Resource(TypedDict, total=False): """Resource. @@ -266,7 +83,7 @@ class Resource(TypedDict, total=False): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.operationtemplates.models.SystemData + :vartype system_data: "SystemData" """ id: str @@ -294,7 +111,7 @@ class TrackedResource(Resource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.operationtemplates.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. @@ -321,13 +138,13 @@ class Order(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.operationtemplates.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: ~azure.resourcemanager.operationtemplates.models.OrderProperties + :vartype properties: "OrderProperties" """ properties: "OrderProperties" @@ -353,48 +170,6 @@ class OrderProperties(TypedDict, total=False): """The provisioning state of the product.""" -class Product(TrackedResource): - """Concrete tracked resource types can be created by aliasing this type using a specific property - type. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.resourcemanager.operationtemplates.models.SystemData - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar location: The geo-location where the resource lives. Required. - :vartype location: str - :ivar properties: The resource-specific properties for this resource. - :vartype properties: ~azure.resourcemanager.operationtemplates.models.ProductProperties - """ - - properties: "ProductProperties" - """The resource-specific properties for this resource.""" - - -class ProductProperties(TypedDict, total=False): - """ProductProperties. - - :ivar product_id: The product ID. - :vartype product_id: str - :ivar provisioning_state: The provisioning state of the product. - :vartype provisioning_state: str - """ - - productId: str - """The product ID.""" - provisioningState: str - """The provisioning state of the product.""" - - class SystemData(TypedDict, total=False): """Metadata pertaining to creation and last modification of the resource. @@ -402,17 +177,16 @@ class SystemData(TypedDict, total=False): :vartype created_by: str :ivar created_by_type: The type of identity that created the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or ~azure.resourcemanager.operationtemplates.models.CreatedByType + :vartype created_by_type: Union[str, "CreatedByType"] :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime + :vartype created_at: str :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str :ivar last_modified_by_type: The type of identity that last modified the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or - ~azure.resourcemanager.operationtemplates.models.CreatedByType + :vartype last_modified_by_type: Union[str, "CreatedByType"] :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime + :vartype last_modified_at: str """ createdBy: str @@ -420,14 +194,14 @@ class SystemData(TypedDict, total=False): createdByType: Union[str, "CreatedByType"] """The type of identity that created the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - createdAt: datetime.datetime + createdAt: str """The timestamp of resource creation (UTC).""" lastModifiedBy: str """The identity that last modified the resource.""" lastModifiedByType: Union[str, "CreatedByType"] """The type of identity that last modified the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - lastModifiedAt: datetime.datetime + lastModifiedAt: str """The timestamp of resource last modification (UTC).""" @@ -445,13 +219,13 @@ class Widget(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.operationtemplates.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: ~azure.resourcemanager.operationtemplates.models.WidgetProperties + :vartype properties: "WidgetProperties" """ properties: "WidgetProperties" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/pyproject.toml index 4aad24d5304d..1221dd81f5dc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-operation-templates/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/operations/_operations.py index ca5d1df089ce..607bbe956920 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/operations/_operations.py @@ -33,7 +33,7 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -66,7 +66,6 @@ ) from .._configuration import ResourcesClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -164,7 +163,7 @@ async def _create_or_replace_initial( self, resource_group_name: str, top_level_tracked_resource_name: str, - resource: Union[_models.TopLevelTrackedResource, JSON, IO[bytes]], + resource: Union[_models.TopLevelTrackedResource, _types.TopLevelTrackedResource, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -271,7 +270,7 @@ async def begin_create_or_replace( self, resource_group_name: str, top_level_tracked_resource_name: str, - resource: JSON, + resource: _types.TopLevelTrackedResource, *, content_type: str = "application/json", **kwargs: Any @@ -284,7 +283,7 @@ async def begin_create_or_replace( :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.resources.types.TopLevelTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -329,7 +328,7 @@ async def begin_create_or_replace( self, resource_group_name: str, top_level_tracked_resource_name: str, - resource: Union[_models.TopLevelTrackedResource, JSON, IO[bytes]], + resource: Union[_models.TopLevelTrackedResource, _types.TopLevelTrackedResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.TopLevelTrackedResource]: """Create a TopLevelTrackedResource. @@ -339,10 +338,10 @@ async def begin_create_or_replace( :type resource_group_name: str :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - TopLevelTrackedResource, JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.resources.models.TopLevelTrackedResource or JSON or - IO[bytes] + :param resource: Resource create parameters. Is either a TopLevelTrackedResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.resources.models.TopLevelTrackedResource or + ~azure.resourcemanager.resources.types.TopLevelTrackedResource or IO[bytes] :return: An instance of AsyncLROPoller that returns TopLevelTrackedResource. The TopLevelTrackedResource is compatible with MutableMapping :rtype: @@ -405,7 +404,7 @@ async def _update_initial( self, resource_group_name: str, top_level_tracked_resource_name: str, - properties: Union[_models.TopLevelTrackedResource, JSON, IO[bytes]], + properties: Union[_models.TopLevelTrackedResource, _types.TopLevelTrackedResource, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -510,7 +509,7 @@ async def begin_update( self, resource_group_name: str, top_level_tracked_resource_name: str, - properties: JSON, + properties: _types.TopLevelTrackedResource, *, content_type: str = "application/json", **kwargs: Any @@ -523,7 +522,7 @@ async def begin_update( :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.resources.types.TopLevelTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -568,7 +567,7 @@ async def begin_update( self, resource_group_name: str, top_level_tracked_resource_name: str, - properties: Union[_models.TopLevelTrackedResource, JSON, IO[bytes]], + properties: Union[_models.TopLevelTrackedResource, _types.TopLevelTrackedResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.TopLevelTrackedResource]: """Update a TopLevelTrackedResource. @@ -578,10 +577,10 @@ async def begin_update( :type resource_group_name: str :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str - :param properties: The resource properties to be updated. Is one of the following types: - TopLevelTrackedResource, JSON, IO[bytes] Required. - :type properties: ~azure.resourcemanager.resources.models.TopLevelTrackedResource or JSON or - IO[bytes] + :param properties: The resource properties to be updated. Is either a TopLevelTrackedResource + type or a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.resources.models.TopLevelTrackedResource or + ~azure.resourcemanager.resources.types.TopLevelTrackedResource or IO[bytes] :return: An instance of AsyncLROPoller that returns TopLevelTrackedResource. The TopLevelTrackedResource is compatible with MutableMapping :rtype: @@ -986,7 +985,7 @@ async def action_sync( self, resource_group_name: str, top_level_tracked_resource_name: str, - body: JSON, + body: _types.NotificationDetails, *, content_type: str = "application/json", **kwargs: Any @@ -999,7 +998,7 @@ async def action_sync( :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str :param body: The content of the action request. Required. - :type body: JSON + :type body: ~azure.resourcemanager.resources.types.NotificationDetails :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1040,7 +1039,7 @@ async def action_sync( self, resource_group_name: str, top_level_tracked_resource_name: str, - body: Union[_models.NotificationDetails, JSON, IO[bytes]], + body: Union[_models.NotificationDetails, _types.NotificationDetails, IO[bytes]], **kwargs: Any ) -> None: """A synchronous resource action that returns no content. @@ -1050,9 +1049,10 @@ async def action_sync( :type resource_group_name: str :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str - :param body: The content of the action request. Is one of the following types: - NotificationDetails, JSON, IO[bytes] Required. - :type body: ~azure.resourcemanager.resources.models.NotificationDetails or JSON or IO[bytes] + :param body: The content of the action request. Is either a NotificationDetails type or a + IO[bytes] type. Required. + :type body: ~azure.resourcemanager.resources.models.NotificationDetails or + ~azure.resourcemanager.resources.types.NotificationDetails or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1213,7 +1213,7 @@ async def _create_or_replace_initial( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - resource: Union[_models.NestedProxyResource, JSON, IO[bytes]], + resource: Union[_models.NestedProxyResource, _types.NestedProxyResource, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -1325,7 +1325,7 @@ async def begin_create_or_replace( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - resource: JSON, + resource: _types.NestedProxyResource, *, content_type: str = "application/json", **kwargs: Any @@ -1340,7 +1340,7 @@ async def begin_create_or_replace( :param nexted_proxy_resource_name: Name of the nested resource. Required. :type nexted_proxy_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.resources.types.NestedProxyResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1389,7 +1389,7 @@ async def begin_create_or_replace( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - resource: Union[_models.NestedProxyResource, JSON, IO[bytes]], + resource: Union[_models.NestedProxyResource, _types.NestedProxyResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.NestedProxyResource]: """Create a NestedProxyResource. @@ -1401,10 +1401,10 @@ async def begin_create_or_replace( :type top_level_tracked_resource_name: str :param nexted_proxy_resource_name: Name of the nested resource. Required. :type nexted_proxy_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - NestedProxyResource, JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.resources.models.NestedProxyResource or JSON or - IO[bytes] + :param resource: Resource create parameters. Is either a NestedProxyResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.resources.models.NestedProxyResource or + ~azure.resourcemanager.resources.types.NestedProxyResource or IO[bytes] :return: An instance of AsyncLROPoller that returns NestedProxyResource. The NestedProxyResource is compatible with MutableMapping :rtype: @@ -1469,7 +1469,7 @@ async def _update_initial( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - properties: Union[_models.NestedProxyResource, JSON, IO[bytes]], + properties: Union[_models.NestedProxyResource, _types.NestedProxyResource, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -1579,7 +1579,7 @@ async def begin_update( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - properties: JSON, + properties: _types.NestedProxyResource, *, content_type: str = "application/json", **kwargs: Any @@ -1594,7 +1594,7 @@ async def begin_update( :param nexted_proxy_resource_name: Name of the nested resource. Required. :type nexted_proxy_resource_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.resources.types.NestedProxyResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1643,7 +1643,7 @@ async def begin_update( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - properties: Union[_models.NestedProxyResource, JSON, IO[bytes]], + properties: Union[_models.NestedProxyResource, _types.NestedProxyResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.NestedProxyResource]: """Update a NestedProxyResource. @@ -1655,10 +1655,10 @@ async def begin_update( :type top_level_tracked_resource_name: str :param nexted_proxy_resource_name: Name of the nested resource. Required. :type nexted_proxy_resource_name: str - :param properties: The resource properties to be updated. Is one of the following types: - NestedProxyResource, JSON, IO[bytes] Required. - :type properties: ~azure.resourcemanager.resources.models.NestedProxyResource or JSON or - IO[bytes] + :param properties: The resource properties to be updated. Is either a NestedProxyResource type + or a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.resources.models.NestedProxyResource or + ~azure.resourcemanager.resources.types.NestedProxyResource or IO[bytes] :return: An instance of AsyncLROPoller that returns NestedProxyResource. The NestedProxyResource is compatible with MutableMapping :rtype: @@ -2042,7 +2042,7 @@ async def get_by_resource_group(self, resource_group_name: str, **kwargs: Any) - async def _create_or_update_initial( self, resource_group_name: str, - resource: Union[_models.SingletonTrackedResource, JSON, IO[bytes]], + resource: Union[_models.SingletonTrackedResource, _types.SingletonTrackedResource, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -2142,7 +2142,12 @@ async def begin_create_or_update( @overload async def begin_create_or_update( - self, resource_group_name: str, resource: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + resource_group_name: str, + resource: _types.SingletonTrackedResource, + *, + content_type: str = "application/json", + **kwargs: Any ) -> AsyncLROPoller[_models.SingletonTrackedResource]: """Create a SingletonTrackedResource. @@ -2150,7 +2155,7 @@ async def begin_create_or_update( Required. :type resource_group_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.resources.types.SingletonTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2186,7 +2191,7 @@ async def begin_create_or_update( async def begin_create_or_update( self, resource_group_name: str, - resource: Union[_models.SingletonTrackedResource, JSON, IO[bytes]], + resource: Union[_models.SingletonTrackedResource, _types.SingletonTrackedResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.SingletonTrackedResource]: """Create a SingletonTrackedResource. @@ -2194,10 +2199,10 @@ async def begin_create_or_update( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param resource: Resource create parameters. Is one of the following types: - SingletonTrackedResource, JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.resources.models.SingletonTrackedResource or JSON or - IO[bytes] + :param resource: Resource create parameters. Is either a SingletonTrackedResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.resources.models.SingletonTrackedResource or + ~azure.resourcemanager.resources.types.SingletonTrackedResource or IO[bytes] :return: An instance of AsyncLROPoller that returns SingletonTrackedResource. The SingletonTrackedResource is compatible with MutableMapping :rtype: @@ -2282,7 +2287,12 @@ async def update( @overload async def update( - self, resource_group_name: str, properties: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + resource_group_name: str, + properties: _types.SingletonTrackedResource, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.SingletonTrackedResource: """Update a SingletonTrackedResource. @@ -2290,7 +2300,7 @@ async def update( Required. :type resource_group_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.resources.types.SingletonTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2324,7 +2334,7 @@ async def update( async def update( self, resource_group_name: str, - properties: Union[_models.SingletonTrackedResource, JSON, IO[bytes]], + properties: Union[_models.SingletonTrackedResource, _types.SingletonTrackedResource, IO[bytes]], **kwargs: Any ) -> _models.SingletonTrackedResource: """Update a SingletonTrackedResource. @@ -2332,10 +2342,10 @@ async def update( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param properties: The resource properties to be updated. Is one of the following types: - SingletonTrackedResource, JSON, IO[bytes] Required. - :type properties: ~azure.resourcemanager.resources.models.SingletonTrackedResource or JSON or - IO[bytes] + :param properties: The resource properties to be updated. Is either a SingletonTrackedResource + type or a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.resources.models.SingletonTrackedResource or + ~azure.resourcemanager.resources.types.SingletonTrackedResource or IO[bytes] :return: SingletonTrackedResource. The SingletonTrackedResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.resources.models.SingletonTrackedResource @@ -2598,7 +2608,7 @@ async def _create_or_update_initial( self, resource_uri: str, extensions_resource_name: str, - resource: Union[_models.ExtensionsResource, JSON, IO[bytes]], + resource: Union[_models.ExtensionsResource, _types.ExtensionsResource, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -2704,7 +2714,7 @@ async def begin_create_or_update( self, resource_uri: str, extensions_resource_name: str, - resource: JSON, + resource: _types.ExtensionsResource, *, content_type: str = "application/json", **kwargs: Any @@ -2717,7 +2727,7 @@ async def begin_create_or_update( :param extensions_resource_name: The name of the ExtensionsResource. Required. :type extensions_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.resources.types.ExtensionsResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2762,7 +2772,7 @@ async def begin_create_or_update( self, resource_uri: str, extensions_resource_name: str, - resource: Union[_models.ExtensionsResource, JSON, IO[bytes]], + resource: Union[_models.ExtensionsResource, _types.ExtensionsResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.ExtensionsResource]: """Create a ExtensionsResource. @@ -2772,9 +2782,10 @@ async def begin_create_or_update( :type resource_uri: str :param extensions_resource_name: The name of the ExtensionsResource. Required. :type extensions_resource_name: str - :param resource: Resource create parameters. Is one of the following types: ExtensionsResource, - JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.resources.models.ExtensionsResource or JSON or IO[bytes] + :param resource: Resource create parameters. Is either a ExtensionsResource type or a IO[bytes] + type. Required. + :type resource: ~azure.resourcemanager.resources.models.ExtensionsResource or + ~azure.resourcemanager.resources.types.ExtensionsResource or IO[bytes] :return: An instance of AsyncLROPoller that returns ExtensionsResource. The ExtensionsResource is compatible with MutableMapping :rtype: @@ -2865,7 +2876,7 @@ async def update( self, resource_uri: str, extensions_resource_name: str, - properties: JSON, + properties: _types.ExtensionsResource, *, content_type: str = "application/json", **kwargs: Any @@ -2878,7 +2889,7 @@ async def update( :param extensions_resource_name: The name of the ExtensionsResource. Required. :type extensions_resource_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.resources.types.ExtensionsResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2919,7 +2930,7 @@ async def update( self, resource_uri: str, extensions_resource_name: str, - properties: Union[_models.ExtensionsResource, JSON, IO[bytes]], + properties: Union[_models.ExtensionsResource, _types.ExtensionsResource, IO[bytes]], **kwargs: Any ) -> _models.ExtensionsResource: """Update a ExtensionsResource. @@ -2929,10 +2940,10 @@ async def update( :type resource_uri: str :param extensions_resource_name: The name of the ExtensionsResource. Required. :type extensions_resource_name: str - :param properties: The resource properties to be updated. Is one of the following types: - ExtensionsResource, JSON, IO[bytes] Required. - :type properties: ~azure.resourcemanager.resources.models.ExtensionsResource or JSON or - IO[bytes] + :param properties: The resource properties to be updated. Is either a ExtensionsResource type + or a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.resources.models.ExtensionsResource or + ~azure.resourcemanager.resources.types.ExtensionsResource or IO[bytes] :return: ExtensionsResource. The ExtensionsResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.resources.models.ExtensionsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -3274,7 +3285,7 @@ async def create_or_update( self, location: str, location_resource_name: str, - resource: JSON, + resource: _types.LocationResource, *, content_type: str = "application/json", **kwargs: Any @@ -3286,7 +3297,7 @@ async def create_or_update( :param location_resource_name: The name of the LocationResource. Required. :type location_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.resources.types.LocationResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3326,7 +3337,7 @@ async def create_or_update( self, location: str, location_resource_name: str, - resource: Union[_models.LocationResource, JSON, IO[bytes]], + resource: Union[_models.LocationResource, _types.LocationResource, IO[bytes]], **kwargs: Any ) -> _models.LocationResource: """Create a LocationResource. @@ -3335,9 +3346,10 @@ async def create_or_update( :type location: str :param location_resource_name: The name of the LocationResource. Required. :type location_resource_name: str - :param resource: Resource create parameters. Is one of the following types: LocationResource, - JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.resources.models.LocationResource or JSON or IO[bytes] + :param resource: Resource create parameters. Is either a LocationResource type or a IO[bytes] + type. Required. + :type resource: ~azure.resourcemanager.resources.models.LocationResource or + ~azure.resourcemanager.resources.types.LocationResource or IO[bytes] :return: LocationResource. The LocationResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.resources.models.LocationResource :raises ~azure.core.exceptions.HttpResponseError: @@ -3440,7 +3452,7 @@ async def update( self, location: str, location_resource_name: str, - properties: JSON, + properties: _types.LocationResource, *, content_type: str = "application/json", **kwargs: Any @@ -3452,7 +3464,7 @@ async def update( :param location_resource_name: The name of the LocationResource. Required. :type location_resource_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.resources.types.LocationResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3492,7 +3504,7 @@ async def update( self, location: str, location_resource_name: str, - properties: Union[_models.LocationResource, JSON, IO[bytes]], + properties: Union[_models.LocationResource, _types.LocationResource, IO[bytes]], **kwargs: Any ) -> _models.LocationResource: """Update a LocationResource. @@ -3501,9 +3513,10 @@ async def update( :type location: str :param location_resource_name: The name of the LocationResource. Required. :type location_resource_name: str - :param properties: The resource properties to be updated. Is one of the following types: - LocationResource, JSON, IO[bytes] Required. - :type properties: ~azure.resourcemanager.resources.models.LocationResource or JSON or IO[bytes] + :param properties: The resource properties to be updated. Is either a LocationResource type or + a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.resources.models.LocationResource or + ~azure.resourcemanager.resources.types.LocationResource or IO[bytes] :return: LocationResource. The LocationResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.resources.models.LocationResource :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/operations/_operations.py index 8f06d69e7fcc..9f32206663dc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/operations/_operations.py @@ -32,12 +32,11 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import ResourcesClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -896,7 +895,7 @@ def _create_or_replace_initial( self, resource_group_name: str, top_level_tracked_resource_name: str, - resource: Union[_models.TopLevelTrackedResource, JSON, IO[bytes]], + resource: Union[_models.TopLevelTrackedResource, _types.TopLevelTrackedResource, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -1003,7 +1002,7 @@ def begin_create_or_replace( self, resource_group_name: str, top_level_tracked_resource_name: str, - resource: JSON, + resource: _types.TopLevelTrackedResource, *, content_type: str = "application/json", **kwargs: Any @@ -1016,7 +1015,7 @@ def begin_create_or_replace( :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.resources.types.TopLevelTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1061,7 +1060,7 @@ def begin_create_or_replace( self, resource_group_name: str, top_level_tracked_resource_name: str, - resource: Union[_models.TopLevelTrackedResource, JSON, IO[bytes]], + resource: Union[_models.TopLevelTrackedResource, _types.TopLevelTrackedResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.TopLevelTrackedResource]: """Create a TopLevelTrackedResource. @@ -1071,10 +1070,10 @@ def begin_create_or_replace( :type resource_group_name: str :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - TopLevelTrackedResource, JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.resources.models.TopLevelTrackedResource or JSON or - IO[bytes] + :param resource: Resource create parameters. Is either a TopLevelTrackedResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.resources.models.TopLevelTrackedResource or + ~azure.resourcemanager.resources.types.TopLevelTrackedResource or IO[bytes] :return: An instance of LROPoller that returns TopLevelTrackedResource. The TopLevelTrackedResource is compatible with MutableMapping :rtype: @@ -1137,7 +1136,7 @@ def _update_initial( self, resource_group_name: str, top_level_tracked_resource_name: str, - properties: Union[_models.TopLevelTrackedResource, JSON, IO[bytes]], + properties: Union[_models.TopLevelTrackedResource, _types.TopLevelTrackedResource, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -1242,7 +1241,7 @@ def begin_update( self, resource_group_name: str, top_level_tracked_resource_name: str, - properties: JSON, + properties: _types.TopLevelTrackedResource, *, content_type: str = "application/json", **kwargs: Any @@ -1255,7 +1254,7 @@ def begin_update( :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.resources.types.TopLevelTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1300,7 +1299,7 @@ def begin_update( self, resource_group_name: str, top_level_tracked_resource_name: str, - properties: Union[_models.TopLevelTrackedResource, JSON, IO[bytes]], + properties: Union[_models.TopLevelTrackedResource, _types.TopLevelTrackedResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.TopLevelTrackedResource]: """Update a TopLevelTrackedResource. @@ -1310,10 +1309,10 @@ def begin_update( :type resource_group_name: str :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str - :param properties: The resource properties to be updated. Is one of the following types: - TopLevelTrackedResource, JSON, IO[bytes] Required. - :type properties: ~azure.resourcemanager.resources.models.TopLevelTrackedResource or JSON or - IO[bytes] + :param properties: The resource properties to be updated. Is either a TopLevelTrackedResource + type or a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.resources.models.TopLevelTrackedResource or + ~azure.resourcemanager.resources.types.TopLevelTrackedResource or IO[bytes] :return: An instance of LROPoller that returns TopLevelTrackedResource. The TopLevelTrackedResource is compatible with MutableMapping :rtype: @@ -1718,7 +1717,7 @@ def action_sync( self, resource_group_name: str, top_level_tracked_resource_name: str, - body: JSON, + body: _types.NotificationDetails, *, content_type: str = "application/json", **kwargs: Any @@ -1731,7 +1730,7 @@ def action_sync( :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str :param body: The content of the action request. Required. - :type body: JSON + :type body: ~azure.resourcemanager.resources.types.NotificationDetails :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1772,7 +1771,7 @@ def action_sync( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, top_level_tracked_resource_name: str, - body: Union[_models.NotificationDetails, JSON, IO[bytes]], + body: Union[_models.NotificationDetails, _types.NotificationDetails, IO[bytes]], **kwargs: Any ) -> None: """A synchronous resource action that returns no content. @@ -1782,9 +1781,10 @@ def action_sync( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param top_level_tracked_resource_name: arm resource name for path. Required. :type top_level_tracked_resource_name: str - :param body: The content of the action request. Is one of the following types: - NotificationDetails, JSON, IO[bytes] Required. - :type body: ~azure.resourcemanager.resources.models.NotificationDetails or JSON or IO[bytes] + :param body: The content of the action request. Is either a NotificationDetails type or a + IO[bytes] type. Required. + :type body: ~azure.resourcemanager.resources.models.NotificationDetails or + ~azure.resourcemanager.resources.types.NotificationDetails or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1945,7 +1945,7 @@ def _create_or_replace_initial( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - resource: Union[_models.NestedProxyResource, JSON, IO[bytes]], + resource: Union[_models.NestedProxyResource, _types.NestedProxyResource, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -2057,7 +2057,7 @@ def begin_create_or_replace( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - resource: JSON, + resource: _types.NestedProxyResource, *, content_type: str = "application/json", **kwargs: Any @@ -2072,7 +2072,7 @@ def begin_create_or_replace( :param nexted_proxy_resource_name: Name of the nested resource. Required. :type nexted_proxy_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.resources.types.NestedProxyResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2121,7 +2121,7 @@ def begin_create_or_replace( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - resource: Union[_models.NestedProxyResource, JSON, IO[bytes]], + resource: Union[_models.NestedProxyResource, _types.NestedProxyResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.NestedProxyResource]: """Create a NestedProxyResource. @@ -2133,10 +2133,10 @@ def begin_create_or_replace( :type top_level_tracked_resource_name: str :param nexted_proxy_resource_name: Name of the nested resource. Required. :type nexted_proxy_resource_name: str - :param resource: Resource create parameters. Is one of the following types: - NestedProxyResource, JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.resources.models.NestedProxyResource or JSON or - IO[bytes] + :param resource: Resource create parameters. Is either a NestedProxyResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.resources.models.NestedProxyResource or + ~azure.resourcemanager.resources.types.NestedProxyResource or IO[bytes] :return: An instance of LROPoller that returns NestedProxyResource. The NestedProxyResource is compatible with MutableMapping :rtype: @@ -2201,7 +2201,7 @@ def _update_initial( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - properties: Union[_models.NestedProxyResource, JSON, IO[bytes]], + properties: Union[_models.NestedProxyResource, _types.NestedProxyResource, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -2311,7 +2311,7 @@ def begin_update( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - properties: JSON, + properties: _types.NestedProxyResource, *, content_type: str = "application/json", **kwargs: Any @@ -2326,7 +2326,7 @@ def begin_update( :param nexted_proxy_resource_name: Name of the nested resource. Required. :type nexted_proxy_resource_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.resources.types.NestedProxyResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2375,7 +2375,7 @@ def begin_update( resource_group_name: str, top_level_tracked_resource_name: str, nexted_proxy_resource_name: str, - properties: Union[_models.NestedProxyResource, JSON, IO[bytes]], + properties: Union[_models.NestedProxyResource, _types.NestedProxyResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.NestedProxyResource]: """Update a NestedProxyResource. @@ -2387,10 +2387,10 @@ def begin_update( :type top_level_tracked_resource_name: str :param nexted_proxy_resource_name: Name of the nested resource. Required. :type nexted_proxy_resource_name: str - :param properties: The resource properties to be updated. Is one of the following types: - NestedProxyResource, JSON, IO[bytes] Required. - :type properties: ~azure.resourcemanager.resources.models.NestedProxyResource or JSON or - IO[bytes] + :param properties: The resource properties to be updated. Is either a NestedProxyResource type + or a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.resources.models.NestedProxyResource or + ~azure.resourcemanager.resources.types.NestedProxyResource or IO[bytes] :return: An instance of LROPoller that returns NestedProxyResource. The NestedProxyResource is compatible with MutableMapping :rtype: @@ -2774,7 +2774,7 @@ def get_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> _mod def _create_or_update_initial( self, resource_group_name: str, - resource: Union[_models.SingletonTrackedResource, JSON, IO[bytes]], + resource: Union[_models.SingletonTrackedResource, _types.SingletonTrackedResource, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -2874,7 +2874,12 @@ def begin_create_or_update( @overload def begin_create_or_update( - self, resource_group_name: str, resource: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + resource_group_name: str, + resource: _types.SingletonTrackedResource, + *, + content_type: str = "application/json", + **kwargs: Any ) -> LROPoller[_models.SingletonTrackedResource]: """Create a SingletonTrackedResource. @@ -2882,7 +2887,7 @@ def begin_create_or_update( Required. :type resource_group_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.resources.types.SingletonTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2918,7 +2923,7 @@ def begin_create_or_update( def begin_create_or_update( self, resource_group_name: str, - resource: Union[_models.SingletonTrackedResource, JSON, IO[bytes]], + resource: Union[_models.SingletonTrackedResource, _types.SingletonTrackedResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.SingletonTrackedResource]: """Create a SingletonTrackedResource. @@ -2926,10 +2931,10 @@ def begin_create_or_update( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param resource: Resource create parameters. Is one of the following types: - SingletonTrackedResource, JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.resources.models.SingletonTrackedResource or JSON or - IO[bytes] + :param resource: Resource create parameters. Is either a SingletonTrackedResource type or a + IO[bytes] type. Required. + :type resource: ~azure.resourcemanager.resources.models.SingletonTrackedResource or + ~azure.resourcemanager.resources.types.SingletonTrackedResource or IO[bytes] :return: An instance of LROPoller that returns SingletonTrackedResource. The SingletonTrackedResource is compatible with MutableMapping :rtype: @@ -3014,7 +3019,12 @@ def update( @overload def update( - self, resource_group_name: str, properties: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + resource_group_name: str, + properties: _types.SingletonTrackedResource, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.SingletonTrackedResource: """Update a SingletonTrackedResource. @@ -3022,7 +3032,7 @@ def update( Required. :type resource_group_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.resources.types.SingletonTrackedResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3056,7 +3066,7 @@ def update( def update( self, resource_group_name: str, - properties: Union[_models.SingletonTrackedResource, JSON, IO[bytes]], + properties: Union[_models.SingletonTrackedResource, _types.SingletonTrackedResource, IO[bytes]], **kwargs: Any ) -> _models.SingletonTrackedResource: """Update a SingletonTrackedResource. @@ -3064,10 +3074,10 @@ def update( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param properties: The resource properties to be updated. Is one of the following types: - SingletonTrackedResource, JSON, IO[bytes] Required. - :type properties: ~azure.resourcemanager.resources.models.SingletonTrackedResource or JSON or - IO[bytes] + :param properties: The resource properties to be updated. Is either a SingletonTrackedResource + type or a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.resources.models.SingletonTrackedResource or + ~azure.resourcemanager.resources.types.SingletonTrackedResource or IO[bytes] :return: SingletonTrackedResource. The SingletonTrackedResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.resources.models.SingletonTrackedResource @@ -3330,7 +3340,7 @@ def _create_or_update_initial( self, resource_uri: str, extensions_resource_name: str, - resource: Union[_models.ExtensionsResource, JSON, IO[bytes]], + resource: Union[_models.ExtensionsResource, _types.ExtensionsResource, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -3436,7 +3446,7 @@ def begin_create_or_update( self, resource_uri: str, extensions_resource_name: str, - resource: JSON, + resource: _types.ExtensionsResource, *, content_type: str = "application/json", **kwargs: Any @@ -3449,7 +3459,7 @@ def begin_create_or_update( :param extensions_resource_name: The name of the ExtensionsResource. Required. :type extensions_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.resources.types.ExtensionsResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3494,7 +3504,7 @@ def begin_create_or_update( self, resource_uri: str, extensions_resource_name: str, - resource: Union[_models.ExtensionsResource, JSON, IO[bytes]], + resource: Union[_models.ExtensionsResource, _types.ExtensionsResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.ExtensionsResource]: """Create a ExtensionsResource. @@ -3504,9 +3514,10 @@ def begin_create_or_update( :type resource_uri: str :param extensions_resource_name: The name of the ExtensionsResource. Required. :type extensions_resource_name: str - :param resource: Resource create parameters. Is one of the following types: ExtensionsResource, - JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.resources.models.ExtensionsResource or JSON or IO[bytes] + :param resource: Resource create parameters. Is either a ExtensionsResource type or a IO[bytes] + type. Required. + :type resource: ~azure.resourcemanager.resources.models.ExtensionsResource or + ~azure.resourcemanager.resources.types.ExtensionsResource or IO[bytes] :return: An instance of LROPoller that returns ExtensionsResource. The ExtensionsResource is compatible with MutableMapping :rtype: @@ -3597,7 +3608,7 @@ def update( self, resource_uri: str, extensions_resource_name: str, - properties: JSON, + properties: _types.ExtensionsResource, *, content_type: str = "application/json", **kwargs: Any @@ -3610,7 +3621,7 @@ def update( :param extensions_resource_name: The name of the ExtensionsResource. Required. :type extensions_resource_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.resources.types.ExtensionsResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3651,7 +3662,7 @@ def update( self, resource_uri: str, extensions_resource_name: str, - properties: Union[_models.ExtensionsResource, JSON, IO[bytes]], + properties: Union[_models.ExtensionsResource, _types.ExtensionsResource, IO[bytes]], **kwargs: Any ) -> _models.ExtensionsResource: """Update a ExtensionsResource. @@ -3661,10 +3672,10 @@ def update( :type resource_uri: str :param extensions_resource_name: The name of the ExtensionsResource. Required. :type extensions_resource_name: str - :param properties: The resource properties to be updated. Is one of the following types: - ExtensionsResource, JSON, IO[bytes] Required. - :type properties: ~azure.resourcemanager.resources.models.ExtensionsResource or JSON or - IO[bytes] + :param properties: The resource properties to be updated. Is either a ExtensionsResource type + or a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.resources.models.ExtensionsResource or + ~azure.resourcemanager.resources.types.ExtensionsResource or IO[bytes] :return: ExtensionsResource. The ExtensionsResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.resources.models.ExtensionsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -4008,7 +4019,7 @@ def create_or_update( self, location: str, location_resource_name: str, - resource: JSON, + resource: _types.LocationResource, *, content_type: str = "application/json", **kwargs: Any @@ -4020,7 +4031,7 @@ def create_or_update( :param location_resource_name: The name of the LocationResource. Required. :type location_resource_name: str :param resource: Resource create parameters. Required. - :type resource: JSON + :type resource: ~azure.resourcemanager.resources.types.LocationResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4060,7 +4071,7 @@ def create_or_update( self, location: str, location_resource_name: str, - resource: Union[_models.LocationResource, JSON, IO[bytes]], + resource: Union[_models.LocationResource, _types.LocationResource, IO[bytes]], **kwargs: Any ) -> _models.LocationResource: """Create a LocationResource. @@ -4069,9 +4080,10 @@ def create_or_update( :type location: str :param location_resource_name: The name of the LocationResource. Required. :type location_resource_name: str - :param resource: Resource create parameters. Is one of the following types: LocationResource, - JSON, IO[bytes] Required. - :type resource: ~azure.resourcemanager.resources.models.LocationResource or JSON or IO[bytes] + :param resource: Resource create parameters. Is either a LocationResource type or a IO[bytes] + type. Required. + :type resource: ~azure.resourcemanager.resources.models.LocationResource or + ~azure.resourcemanager.resources.types.LocationResource or IO[bytes] :return: LocationResource. The LocationResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.resources.models.LocationResource :raises ~azure.core.exceptions.HttpResponseError: @@ -4174,7 +4186,7 @@ def update( self, location: str, location_resource_name: str, - properties: JSON, + properties: _types.LocationResource, *, content_type: str = "application/json", **kwargs: Any @@ -4186,7 +4198,7 @@ def update( :param location_resource_name: The name of the LocationResource. Required. :type location_resource_name: str :param properties: The resource properties to be updated. Required. - :type properties: JSON + :type properties: ~azure.resourcemanager.resources.types.LocationResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4226,7 +4238,7 @@ def update( self, location: str, location_resource_name: str, - properties: Union[_models.LocationResource, JSON, IO[bytes]], + properties: Union[_models.LocationResource, _types.LocationResource, IO[bytes]], **kwargs: Any ) -> _models.LocationResource: """Update a LocationResource. @@ -4235,9 +4247,10 @@ def update( :type location: str :param location_resource_name: The name of the LocationResource. Required. :type location_resource_name: str - :param properties: The resource properties to be updated. Is one of the following types: - LocationResource, JSON, IO[bytes] Required. - :type properties: ~azure.resourcemanager.resources.models.LocationResource or JSON or IO[bytes] + :param properties: The resource properties to be updated. Is either a LocationResource type or + a IO[bytes] type. Required. + :type properties: ~azure.resourcemanager.resources.models.LocationResource or + ~azure.resourcemanager.resources.types.LocationResource or IO[bytes] :return: LocationResource. The LocationResource is compatible with MutableMapping :rtype: ~azure.resourcemanager.resources.models.LocationResource :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/types.py index f94ef595f7dd..1bff7dd074cb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/azure/resourcemanager/resources/types.py @@ -7,67 +7,13 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -from typing import Any, TYPE_CHECKING, Union +from typing import TYPE_CHECKING, Union from typing_extensions import Required, TypedDict if TYPE_CHECKING: from .models import CreatedByType, ProvisioningState -class ErrorAdditionalInfo(TypedDict, total=False): - """The resource management error additional info. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - type: str - """The additional info type.""" - info: Any - """The additional info.""" - - -class ErrorDetail(TypedDict, total=False): - """The error detail. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.resourcemanager.resources.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.resourcemanager.resources.models.ErrorAdditionalInfo] - """ - - code: str - """The error code.""" - message: str - """The error message.""" - target: str - """The error target.""" - details: list["ErrorDetail"] - """The error details.""" - additionalInfo: list["ErrorAdditionalInfo"] - """The error additional info.""" - - -class ErrorResponse(TypedDict, total=False): - """Error response. - - :ivar error: The error object. - :vartype error: ~azure.resourcemanager.resources.models.ErrorDetail - """ - - error: "ErrorDetail" - """The error object.""" - - class Resource(TypedDict, total=False): """Resource. @@ -81,7 +27,7 @@ class Resource(TypedDict, total=False): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.resources.models.SystemData + :vartype system_data: "SystemData" """ id: str @@ -109,7 +55,7 @@ class ExtensionResource(Resource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.resources.models.SystemData + :vartype system_data: "SystemData" """ @@ -127,9 +73,9 @@ class ExtensionsResource(ExtensionResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.resources.models.SystemData + :vartype system_data: "SystemData" :ivar properties: The resource-specific properties for this resource. - :vartype properties: ~azure.resourcemanager.resources.models.ExtensionsResourceProperties + :vartype properties: "ExtensionsResourceProperties" """ properties: "ExtensionsResourceProperties" @@ -143,7 +89,7 @@ class ExtensionsResourceProperties(TypedDict, total=False): :vartype description: str :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", "Failed", "Canceled", "Provisioning", "Updating", "Deleting", and "Accepted". - :vartype provisioning_state: str or ~azure.resourcemanager.resources.models.ProvisioningState + :vartype provisioning_state: Union[str, "ProvisioningState"] """ description: str @@ -166,7 +112,7 @@ class ProxyResource(Resource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.resources.models.SystemData + :vartype system_data: "SystemData" """ @@ -184,9 +130,9 @@ class LocationResource(ProxyResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.resources.models.SystemData + :vartype system_data: "SystemData" :ivar properties: The resource-specific properties for this resource. - :vartype properties: ~azure.resourcemanager.resources.models.LocationResourceProperties + :vartype properties: "LocationResourceProperties" """ properties: "LocationResourceProperties" @@ -200,7 +146,7 @@ class LocationResourceProperties(TypedDict, total=False): :vartype description: str :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", "Failed", "Canceled", "Provisioning", "Updating", "Deleting", and "Accepted". - :vartype provisioning_state: str or ~azure.resourcemanager.resources.models.ProvisioningState + :vartype provisioning_state: Union[str, "ProvisioningState"] """ description: str @@ -223,9 +169,9 @@ class NestedProxyResource(ProxyResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.resources.models.SystemData + :vartype system_data: "SystemData" :ivar properties: The resource-specific properties for this resource. - :vartype properties: ~azure.resourcemanager.resources.models.NestedProxyResourceProperties + :vartype properties: "NestedProxyResourceProperties" """ properties: "NestedProxyResourceProperties" @@ -237,7 +183,7 @@ class NestedProxyResourceProperties(TypedDict, total=False): :ivar provisioning_state: Provisioning State of the nested child Resource. Known values are: "Succeeded", "Failed", "Canceled", "Provisioning", "Updating", "Deleting", and "Accepted". - :vartype provisioning_state: str or ~azure.resourcemanager.resources.models.ProvisioningState + :vartype provisioning_state: Union[str, "ProvisioningState"] :ivar description: Nested resource description. :vartype description: str """ @@ -277,7 +223,7 @@ class TrackedResource(Resource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.resources.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. @@ -304,13 +250,13 @@ class SingletonTrackedResource(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.resources.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: ~azure.resourcemanager.resources.models.SingletonTrackedResourceProperties + :vartype properties: "SingletonTrackedResourceProperties" """ properties: "SingletonTrackedResourceProperties" @@ -322,7 +268,7 @@ class SingletonTrackedResourceProperties(TypedDict, total=False): :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", "Failed", "Canceled", "Provisioning", "Updating", "Deleting", and "Accepted". - :vartype provisioning_state: str or ~azure.resourcemanager.resources.models.ProvisioningState + :vartype provisioning_state: Union[str, "ProvisioningState"] :ivar description: The description of the resource. :vartype description: str """ @@ -341,16 +287,16 @@ class SystemData(TypedDict, total=False): :vartype created_by: str :ivar created_by_type: The type of identity that created the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or ~azure.resourcemanager.resources.models.CreatedByType + :vartype created_by_type: Union[str, "CreatedByType"] :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime + :vartype created_at: str :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str :ivar last_modified_by_type: The type of identity that last modified the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or ~azure.resourcemanager.resources.models.CreatedByType + :vartype last_modified_by_type: Union[str, "CreatedByType"] :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime + :vartype last_modified_at: str """ createdBy: str @@ -358,14 +304,14 @@ class SystemData(TypedDict, total=False): createdByType: Union[str, "CreatedByType"] """The type of identity that created the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - createdAt: datetime.datetime + createdAt: str """The timestamp of resource creation (UTC).""" lastModifiedBy: str """The identity that last modified the resource.""" lastModifiedByType: Union[str, "CreatedByType"] """The type of identity that last modified the resource. Known values are: \"User\", \"Application\", \"ManagedIdentity\", and \"Key\".""" - lastModifiedAt: datetime.datetime + lastModifiedAt: str """The timestamp of resource last modification (UTC).""" @@ -383,13 +329,13 @@ class TopLevelTrackedResource(TrackedResource): :vartype type: str :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.resourcemanager.resources.models.SystemData + :vartype system_data: "SystemData" :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar properties: The resource-specific properties for this resource. - :vartype properties: ~azure.resourcemanager.resources.models.TopLevelTrackedResourceProperties + :vartype properties: "TopLevelTrackedResourceProperties" """ properties: "TopLevelTrackedResourceProperties" @@ -401,7 +347,7 @@ class TopLevelTrackedResourceProperties(TypedDict, total=False): :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", "Failed", "Canceled", "Provisioning", "Updating", "Deleting", and "Accepted". - :vartype provisioning_state: str or ~azure.resourcemanager.resources.models.ProvisioningState + :vartype provisioning_state: Union[str, "ProvisioningState"] :ivar description: The description of the resource. :vartype description: str """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/pyproject.toml index 726d227e2e1a..4d921182eedf 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-resource-manager-resources/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/azure/specialheaders/xmsclientrequestid/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/pyproject.toml index 9748c4d8ef9d..b313f159a0aa 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-client-request-id/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/azure/specialheaders/conditionalrequest/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/pyproject.toml index e94b7818a2c9..a5d8da8191e2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-special-headers-conditional-request/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/pyproject.toml index e72ff6a53651..e5583df2e924 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_operations/_operations.py index faf83e726175..8857b1e3736d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_operations/_operations.py @@ -26,14 +26,13 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import PreviewVersionClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC from .._validation import api_version_validation -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -211,14 +210,19 @@ def update_widget_color( @overload def update_widget_color( - self, id: str, color_update: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + id: str, + color_update: _types.UpdateWidgetColorRequest, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> Optional[_models.Widget]: """Update widget color (preview only). :param id: Required. :type id: str :param color_update: Required. - :type color_update: JSON + :type color_update: ~specs.azure.versioning.previewversion.types.UpdateWidgetColorRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -252,16 +256,18 @@ def update_widget_color( api_versions_list=["2024-12-01-preview"], ) def update_widget_color( - self, id: str, color_update: Union[_models.UpdateWidgetColorRequest, JSON, IO[bytes]], **kwargs: Any + self, + id: str, + color_update: Union[_models.UpdateWidgetColorRequest, _types.UpdateWidgetColorRequest, IO[bytes]], + **kwargs: Any ) -> Optional[_models.Widget]: """Update widget color (preview only). :param id: Required. :type id: str - :param color_update: Is one of the following types: UpdateWidgetColorRequest, JSON, IO[bytes] - Required. + :param color_update: Is either a UpdateWidgetColorRequest type or a IO[bytes] type. Required. :type color_update: ~specs.azure.versioning.previewversion.models.UpdateWidgetColorRequest or - JSON or IO[bytes] + ~specs.azure.versioning.previewversion.types.UpdateWidgetColorRequest or IO[bytes] :return: Widget or None. The Widget is compatible with MutableMapping :rtype: ~specs.azure.versioning.previewversion.models.Widget or None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_operations/_operations.py index 956d5e7fdcc6..9607bfd80cdd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_preview_version_get_widget_request, build_preview_version_list_widgets_request, @@ -38,7 +38,6 @@ from ..._validation import api_version_validation from .._configuration import PreviewVersionClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -135,14 +134,19 @@ async def update_widget_color( @overload async def update_widget_color( - self, id: str, color_update: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + id: str, + color_update: _types.UpdateWidgetColorRequest, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> Optional[_models.Widget]: """Update widget color (preview only). :param id: Required. :type id: str :param color_update: Required. - :type color_update: JSON + :type color_update: ~specs.azure.versioning.previewversion.types.UpdateWidgetColorRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -176,16 +180,18 @@ async def update_widget_color( api_versions_list=["2024-12-01-preview"], ) async def update_widget_color( - self, id: str, color_update: Union[_models.UpdateWidgetColorRequest, JSON, IO[bytes]], **kwargs: Any + self, + id: str, + color_update: Union[_models.UpdateWidgetColorRequest, _types.UpdateWidgetColorRequest, IO[bytes]], + **kwargs: Any ) -> Optional[_models.Widget]: """Update widget color (preview only). :param id: Required. :type id: str - :param color_update: Is one of the following types: UpdateWidgetColorRequest, JSON, IO[bytes] - Required. + :param color_update: Is either a UpdateWidgetColorRequest type or a IO[bytes] type. Required. :type color_update: ~specs.azure.versioning.previewversion.models.UpdateWidgetColorRequest or - JSON or IO[bytes] + ~specs.azure.versioning.previewversion.types.UpdateWidgetColorRequest or IO[bytes] :return: Widget or None. The Widget is compatible with MutableMapping :rtype: ~specs.azure.versioning.previewversion.models.Widget or None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/types.py index 5660f445edbd..ca44b4e03a8a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-versioning-previewversion/specs/azure/versioning/previewversion/types.py @@ -9,17 +9,6 @@ from typing_extensions import Required, TypedDict -class ListWidgetsResponse(TypedDict, total=False): - """ListWidgetsResponse. - - :ivar widgets: Required. - :vartype widgets: list[~specs.azure.versioning.previewversion.models.Widget] - """ - - widgets: Required[list["Widget"]] - """Required.""" - - class UpdateWidgetColorRequest(TypedDict, total=False): """Update widget color request. @@ -29,22 +18,3 @@ class UpdateWidgetColorRequest(TypedDict, total=False): color: Required[str] """New color for the widget. Required.""" - - -class Widget(TypedDict, total=False): - """A simple model for testing. - - :ivar id: Widget identifier. Required. - :vartype id: str - :ivar name: Widget name. Required. - :vartype name: str - :ivar color: Widget color, only available in preview version. - :vartype color: str - """ - - id: Required[str] - """Widget identifier. Required.""" - name: Required[str] - """Widget name. Required.""" - color: str - """Widget color, only available in preview version.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/first/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/first/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/first/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/first/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/sub/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/sub/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/sub/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/second/sub/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/pyproject.toml index c1392c755547..4e6904d8401c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/operations/_operations.py index 151968623d59..e6aa1e4dbeea 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/operations/_operations.py @@ -28,12 +28,11 @@ from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -from ...firstnamespace import models as _firstnamespace_models3 +from ...firstnamespace import models as _firstnamespace_models3, types as _types_firstnamespace_models3 from ...operations._operations import build_first_operations_first_request, build_second_operations_second_request -from ...secondnamespace import models as _secondnamespace_models3 +from ...secondnamespace import models as _secondnamespace_models3, types as _types_secondnamespace_models3 from .._configuration import EnumConflictClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -73,12 +72,12 @@ async def first( @overload async def first( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_firstnamespace_models3.FirstModel, *, content_type: str = "application/json", **kwargs: Any ) -> _firstnamespace_models3.FirstModel: """Operation using first namespace Status enum. :param body: Required. - :type body: JSON + :type body: ~client.naming.enumconflict.firstnamespace.types.FirstModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -105,12 +104,15 @@ async def first( @distributed_trace_async async def first( - self, body: Union[_firstnamespace_models3.FirstModel, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_firstnamespace_models3.FirstModel, _types_firstnamespace_models3.FirstModel, IO[bytes]], + **kwargs: Any ) -> _firstnamespace_models3.FirstModel: """Operation using first namespace Status enum. - :param body: Is one of the following types: FirstModel, JSON, IO[bytes] Required. - :type body: ~client.naming.enumconflict.firstnamespace.models.FirstModel or JSON or IO[bytes] + :param body: Is either a FirstModel type or a IO[bytes] type. Required. + :type body: ~client.naming.enumconflict.firstnamespace.models.FirstModel or + ~client.naming.enumconflict.firstnamespace.types.FirstModel or IO[bytes] :return: FirstModel. The FirstModel is compatible with MutableMapping :rtype: ~client.naming.enumconflict.firstnamespace.models.FirstModel :raises ~azure.core.exceptions.HttpResponseError: @@ -210,12 +212,12 @@ async def second( @overload async def second( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_secondnamespace_models3.SecondModel, *, content_type: str = "application/json", **kwargs: Any ) -> _secondnamespace_models3.SecondModel: """Operation using second namespace Status enum. :param body: Required. - :type body: JSON + :type body: ~client.naming.enumconflict.secondnamespace.types.SecondModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -242,12 +244,15 @@ async def second( @distributed_trace_async async def second( - self, body: Union[_secondnamespace_models3.SecondModel, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_secondnamespace_models3.SecondModel, _types_secondnamespace_models3.SecondModel, IO[bytes]], + **kwargs: Any ) -> _secondnamespace_models3.SecondModel: """Operation using second namespace Status enum. - :param body: Is one of the following types: SecondModel, JSON, IO[bytes] Required. - :type body: ~client.naming.enumconflict.secondnamespace.models.SecondModel or JSON or IO[bytes] + :param body: Is either a SecondModel type or a IO[bytes] type. Required. + :type body: ~client.naming.enumconflict.secondnamespace.models.SecondModel or + ~client.naming.enumconflict.secondnamespace.types.SecondModel or IO[bytes] :return: SecondModel. The SecondModel is compatible with MutableMapping :rtype: ~client.naming.enumconflict.secondnamespace.models.SecondModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/firstnamespace/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/firstnamespace/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/firstnamespace/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/firstnamespace/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/firstnamespace/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/firstnamespace/types.py index a699daabd830..e642bc10bd44 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/firstnamespace/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/firstnamespace/types.py @@ -17,7 +17,7 @@ class FirstModel(TypedDict, total=False): """FirstModel. :ivar status: Status from first namespace. Required. Known values are: "active" and "inactive". - :vartype status: str or ~client.naming.enumconflict.firstnamespace.models.Status + :vartype status: Union[str, "Status"] :ivar name: Name of the item. Required. :vartype name: str """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/operations/_operations.py index ff0cf014aea4..0ad1664230f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/operations/_operations.py @@ -29,10 +29,9 @@ from .._configuration import EnumConflictClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -from ..firstnamespace import models as _firstnamespace_models2 -from ..secondnamespace import models as _secondnamespace_models2 +from ..firstnamespace import models as _firstnamespace_models2, types as _types_firstnamespace_models2 +from ..secondnamespace import models as _secondnamespace_models2, types as _types_secondnamespace_models2 -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -109,12 +108,12 @@ def first( @overload def first( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_firstnamespace_models2.FirstModel, *, content_type: str = "application/json", **kwargs: Any ) -> _firstnamespace_models2.FirstModel: """Operation using first namespace Status enum. :param body: Required. - :type body: JSON + :type body: ~client.naming.enumconflict.firstnamespace.types.FirstModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -141,12 +140,15 @@ def first( @distributed_trace def first( - self, body: Union[_firstnamespace_models2.FirstModel, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_firstnamespace_models2.FirstModel, _types_firstnamespace_models2.FirstModel, IO[bytes]], + **kwargs: Any ) -> _firstnamespace_models2.FirstModel: """Operation using first namespace Status enum. - :param body: Is one of the following types: FirstModel, JSON, IO[bytes] Required. - :type body: ~client.naming.enumconflict.firstnamespace.models.FirstModel or JSON or IO[bytes] + :param body: Is either a FirstModel type or a IO[bytes] type. Required. + :type body: ~client.naming.enumconflict.firstnamespace.models.FirstModel or + ~client.naming.enumconflict.firstnamespace.types.FirstModel or IO[bytes] :return: FirstModel. The FirstModel is compatible with MutableMapping :rtype: ~client.naming.enumconflict.firstnamespace.models.FirstModel :raises ~azure.core.exceptions.HttpResponseError: @@ -246,12 +248,12 @@ def second( @overload def second( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_secondnamespace_models2.SecondModel, *, content_type: str = "application/json", **kwargs: Any ) -> _secondnamespace_models2.SecondModel: """Operation using second namespace Status enum. :param body: Required. - :type body: JSON + :type body: ~client.naming.enumconflict.secondnamespace.types.SecondModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -278,12 +280,15 @@ def second( @distributed_trace def second( - self, body: Union[_secondnamespace_models2.SecondModel, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_secondnamespace_models2.SecondModel, _types_secondnamespace_models2.SecondModel, IO[bytes]], + **kwargs: Any ) -> _secondnamespace_models2.SecondModel: """Operation using second namespace Status enum. - :param body: Is one of the following types: SecondModel, JSON, IO[bytes] Required. - :type body: ~client.naming.enumconflict.secondnamespace.models.SecondModel or JSON or IO[bytes] + :param body: Is either a SecondModel type or a IO[bytes] type. Required. + :type body: ~client.naming.enumconflict.secondnamespace.models.SecondModel or + ~client.naming.enumconflict.secondnamespace.types.SecondModel or IO[bytes] :return: SecondModel. The SecondModel is compatible with MutableMapping :rtype: ~client.naming.enumconflict.secondnamespace.models.SecondModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/secondnamespace/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/secondnamespace/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/secondnamespace/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/secondnamespace/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/secondnamespace/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/secondnamespace/types.py index 0db965a61148..a0186628ddcf 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/secondnamespace/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/client/naming/enumconflict/secondnamespace/types.py @@ -18,7 +18,7 @@ class SecondModel(TypedDict, total=False): :ivar status: Status from second namespace. Required. Known values are: "running" and "stopped". - :vartype status: str or ~client.naming.enumconflict.secondnamespace.models.SecondStatus + :vartype status: Union[str, "SecondStatus"] :ivar description: Description of the item. Required. :vartype description: str """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/pyproject.toml index 28e8995c6bc8..a9e793f8cb5c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-enum-conflict/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/README.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/aio/operations/_operations.py index 2bf3d872e4bb..3391d52c471b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/aio/operations/_operations.py @@ -25,7 +25,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models, types +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer from ..._utils.utils import ClientMixinABC @@ -83,7 +83,7 @@ async def client( @overload async def client( - self, body: types.ClientNameModel, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ClientNameModel, *, content_type: str = "application/json", **kwargs: Any ) -> None: """client. @@ -113,7 +113,7 @@ async def client(self, body: IO[bytes], *, content_type: str = "application/json @distributed_trace_async async def client( - self, body: Union[_models.ClientNameModel, types.ClientNameModel, IO[bytes]], **kwargs: Any + self, body: Union[_models.ClientNameModel, _types.ClientNameModel, IO[bytes]], **kwargs: Any ) -> None: """client. @@ -188,7 +188,7 @@ async def language( @overload async def language( - self, body: types.LanguageClientNameModel, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.LanguageClientNameModel, *, content_type: str = "application/json", **kwargs: Any ) -> None: """language. @@ -218,7 +218,7 @@ async def language(self, body: IO[bytes], *, content_type: str = "application/js @distributed_trace_async async def language( - self, body: Union[_models.LanguageClientNameModel, types.LanguageClientNameModel, IO[bytes]], **kwargs: Any + self, body: Union[_models.LanguageClientNameModel, _types.LanguageClientNameModel, IO[bytes]], **kwargs: Any ) -> None: """language. @@ -293,7 +293,7 @@ async def compatible_with_encoded_name( @overload async def compatible_with_encoded_name( - self, body: types.ClientNameAndJsonEncodedNameModel, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ClientNameAndJsonEncodedNameModel, *, content_type: str = "application/json", **kwargs: Any ) -> None: """compatible_with_encoded_name. @@ -326,7 +326,7 @@ async def compatible_with_encoded_name( @distributed_trace_async async def compatible_with_encoded_name( self, - body: Union[_models.ClientNameAndJsonEncodedNameModel, types.ClientNameAndJsonEncodedNameModel, IO[bytes]], + body: Union[_models.ClientNameAndJsonEncodedNameModel, _types.ClientNameAndJsonEncodedNameModel, IO[bytes]], **kwargs: Any ) -> None: """compatible_with_encoded_name. @@ -529,7 +529,7 @@ async def client(self, body: _models.ClientModel, *, content_type: str = "applic """ @overload - async def client(self, body: types.ClientModel, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def client(self, body: _types.ClientModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """client. :param body: Required. @@ -557,7 +557,7 @@ async def client(self, body: IO[bytes], *, content_type: str = "application/json """ @distributed_trace_async - async def client(self, body: Union[_models.ClientModel, types.ClientModel, IO[bytes]], **kwargs: Any) -> None: + async def client(self, body: Union[_models.ClientModel, _types.ClientModel, IO[bytes]], **kwargs: Any) -> None: """client. :param body: Is either a ClientModel type or a IO[bytes] type. Required. @@ -630,7 +630,9 @@ async def language( """ @overload - async def language(self, body: types.PythonModel, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def language( + self, body: _types.PythonModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """language. :param body: Required. @@ -658,7 +660,7 @@ async def language(self, body: IO[bytes], *, content_type: str = "application/js """ @distributed_trace_async - async def language(self, body: Union[_models.PythonModel, types.PythonModel, IO[bytes]], **kwargs: Any) -> None: + async def language(self, body: Union[_models.PythonModel, _types.PythonModel, IO[bytes]], **kwargs: Any) -> None: """language. :param body: Is either a PythonModel type or a IO[bytes] type. Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/operations/_operations.py index 473534d1a442..01c1262f85f5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/client/naming/typeddict/operations/_operations.py @@ -25,7 +25,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models, types +from .. import models as _models, types as _types from .._configuration import NamingClientConfiguration from .._utils.model_base import SdkJSONEncoder from .._utils.serialization import Deserializer, Serializer @@ -204,7 +204,7 @@ def client(self, body: _models.ClientNameModel, *, content_type: str = "applicat """ @overload - def client(self, body: types.ClientNameModel, *, content_type: str = "application/json", **kwargs: Any) -> None: + def client(self, body: _types.ClientNameModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """client. :param body: Required. @@ -233,7 +233,7 @@ def client(self, body: IO[bytes], *, content_type: str = "application/json", **k @distributed_trace def client( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ClientNameModel, types.ClientNameModel, IO[bytes]], **kwargs: Any + self, body: Union[_models.ClientNameModel, _types.ClientNameModel, IO[bytes]], **kwargs: Any ) -> None: """client. @@ -308,7 +308,7 @@ def language( @overload def language( - self, body: types.LanguageClientNameModel, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.LanguageClientNameModel, *, content_type: str = "application/json", **kwargs: Any ) -> None: """language. @@ -338,7 +338,7 @@ def language(self, body: IO[bytes], *, content_type: str = "application/json", * @distributed_trace def language( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.LanguageClientNameModel, types.LanguageClientNameModel, IO[bytes]], **kwargs: Any + self, body: Union[_models.LanguageClientNameModel, _types.LanguageClientNameModel, IO[bytes]], **kwargs: Any ) -> None: """language. @@ -413,7 +413,7 @@ def compatible_with_encoded_name( @overload def compatible_with_encoded_name( - self, body: types.ClientNameAndJsonEncodedNameModel, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ClientNameAndJsonEncodedNameModel, *, content_type: str = "application/json", **kwargs: Any ) -> None: """compatible_with_encoded_name. @@ -446,7 +446,7 @@ def compatible_with_encoded_name( @distributed_trace def compatible_with_encoded_name( # pylint: disable=inconsistent-return-statements self, - body: Union[_models.ClientNameAndJsonEncodedNameModel, types.ClientNameAndJsonEncodedNameModel, IO[bytes]], + body: Union[_models.ClientNameAndJsonEncodedNameModel, _types.ClientNameAndJsonEncodedNameModel, IO[bytes]], **kwargs: Any ) -> None: """compatible_with_encoded_name. @@ -649,7 +649,7 @@ def client(self, body: _models.ClientModel, *, content_type: str = "application/ """ @overload - def client(self, body: types.ClientModel, *, content_type: str = "application/json", **kwargs: Any) -> None: + def client(self, body: _types.ClientModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """client. :param body: Required. @@ -678,7 +678,7 @@ def client(self, body: IO[bytes], *, content_type: str = "application/json", **k @distributed_trace def client( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ClientModel, types.ClientModel, IO[bytes]], **kwargs: Any + self, body: Union[_models.ClientModel, _types.ClientModel, IO[bytes]], **kwargs: Any ) -> None: """client. @@ -750,7 +750,7 @@ def language(self, body: _models.PythonModel, *, content_type: str = "applicatio """ @overload - def language(self, body: types.PythonModel, *, content_type: str = "application/json", **kwargs: Any) -> None: + def language(self, body: _types.PythonModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """language. :param body: Required. @@ -779,7 +779,7 @@ def language(self, body: IO[bytes], *, content_type: str = "application/json", * @distributed_trace def language( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PythonModel, types.PythonModel, IO[bytes]], **kwargs: Any + self, body: Union[_models.PythonModel, _types.PythonModel, IO[bytes]], **kwargs: Any ) -> None: """language. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/pyproject.toml index 321e8522c255..b64a90b88ebd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming-typeddict/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/operations/_operations.py index c83093f5645a..babaa7b80c04 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/operations/_operations.py @@ -25,7 +25,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer from ..._utils.utils import ClientMixinABC @@ -44,7 +44,6 @@ ) from .._configuration import NamingClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -83,11 +82,13 @@ async def client( """ @overload - async def client(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def client( + self, body: _types.ClientNameModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """client. :param body: Required. - :type body: JSON + :type body: ~client.naming.main.types.ClientNameModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -111,11 +112,14 @@ async def client(self, body: IO[bytes], *, content_type: str = "application/json """ @distributed_trace_async - async def client(self, body: Union[_models.ClientNameModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def client( + self, body: Union[_models.ClientNameModel, _types.ClientNameModel, IO[bytes]], **kwargs: Any + ) -> None: """client. - :param body: Is one of the following types: ClientNameModel, JSON, IO[bytes] Required. - :type body: ~client.naming.main.models.ClientNameModel or JSON or IO[bytes] + :param body: Is either a ClientNameModel type or a IO[bytes] type. Required. + :type body: ~client.naming.main.models.ClientNameModel or + ~client.naming.main.types.ClientNameModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -183,11 +187,13 @@ async def language( """ @overload - async def language(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def language( + self, body: _types.LanguageClientNameModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """language. :param body: Required. - :type body: JSON + :type body: ~client.naming.main.types.LanguageClientNameModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -211,11 +217,14 @@ async def language(self, body: IO[bytes], *, content_type: str = "application/js """ @distributed_trace_async - async def language(self, body: Union[_models.LanguageClientNameModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def language( + self, body: Union[_models.LanguageClientNameModel, _types.LanguageClientNameModel, IO[bytes]], **kwargs: Any + ) -> None: """language. - :param body: Is one of the following types: LanguageClientNameModel, JSON, IO[bytes] Required. - :type body: ~client.naming.main.models.LanguageClientNameModel or JSON or IO[bytes] + :param body: Is either a LanguageClientNameModel type or a IO[bytes] type. Required. + :type body: ~client.naming.main.models.LanguageClientNameModel or + ~client.naming.main.types.LanguageClientNameModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -284,12 +293,12 @@ async def compatible_with_encoded_name( @overload async def compatible_with_encoded_name( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ClientNameAndJsonEncodedNameModel, *, content_type: str = "application/json", **kwargs: Any ) -> None: """compatible_with_encoded_name. :param body: Required. - :type body: JSON + :type body: ~client.naming.main.types.ClientNameAndJsonEncodedNameModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -316,13 +325,15 @@ async def compatible_with_encoded_name( @distributed_trace_async async def compatible_with_encoded_name( - self, body: Union[_models.ClientNameAndJsonEncodedNameModel, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ClientNameAndJsonEncodedNameModel, _types.ClientNameAndJsonEncodedNameModel, IO[bytes]], + **kwargs: Any ) -> None: """compatible_with_encoded_name. - :param body: Is one of the following types: ClientNameAndJsonEncodedNameModel, JSON, IO[bytes] - Required. - :type body: ~client.naming.main.models.ClientNameAndJsonEncodedNameModel or JSON or IO[bytes] + :param body: Is either a ClientNameAndJsonEncodedNameModel type or a IO[bytes] type. Required. + :type body: ~client.naming.main.models.ClientNameAndJsonEncodedNameModel or + ~client.naming.main.types.ClientNameAndJsonEncodedNameModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -518,11 +529,11 @@ async def client(self, body: _models.ClientModel, *, content_type: str = "applic """ @overload - async def client(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def client(self, body: _types.ClientModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """client. :param body: Required. - :type body: JSON + :type body: ~client.naming.main.types.ClientModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -546,11 +557,12 @@ async def client(self, body: IO[bytes], *, content_type: str = "application/json """ @distributed_trace_async - async def client(self, body: Union[_models.ClientModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def client(self, body: Union[_models.ClientModel, _types.ClientModel, IO[bytes]], **kwargs: Any) -> None: """client. - :param body: Is one of the following types: ClientModel, JSON, IO[bytes] Required. - :type body: ~client.naming.main.models.ClientModel or JSON or IO[bytes] + :param body: Is either a ClientModel type or a IO[bytes] type. Required. + :type body: ~client.naming.main.models.ClientModel or ~client.naming.main.types.ClientModel or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -618,11 +630,13 @@ async def language( """ @overload - async def language(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def language( + self, body: _types.PythonModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """language. :param body: Required. - :type body: JSON + :type body: ~client.naming.main.types.PythonModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -646,11 +660,12 @@ async def language(self, body: IO[bytes], *, content_type: str = "application/js """ @distributed_trace_async - async def language(self, body: Union[_models.PythonModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def language(self, body: Union[_models.PythonModel, _types.PythonModel, IO[bytes]], **kwargs: Any) -> None: """language. - :param body: Is one of the following types: PythonModel, JSON, IO[bytes] Required. - :type body: ~client.naming.main.models.PythonModel or JSON or IO[bytes] + :param body: Is either a PythonModel type or a IO[bytes] type. Required. + :type body: ~client.naming.main.models.PythonModel or ~client.naming.main.types.PythonModel or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/operations/_operations.py index b9de13cda7f5..74986dfd6c53 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/operations/_operations.py @@ -25,13 +25,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import NamingClientConfiguration from .._utils.model_base import SdkJSONEncoder from .._utils.serialization import Deserializer, Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -205,11 +204,11 @@ def client(self, body: _models.ClientNameModel, *, content_type: str = "applicat """ @overload - def client(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def client(self, body: _types.ClientNameModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """client. :param body: Required. - :type body: JSON + :type body: ~client.naming.main.types.ClientNameModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -234,12 +233,13 @@ def client(self, body: IO[bytes], *, content_type: str = "application/json", **k @distributed_trace def client( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ClientNameModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ClientNameModel, _types.ClientNameModel, IO[bytes]], **kwargs: Any ) -> None: """client. - :param body: Is one of the following types: ClientNameModel, JSON, IO[bytes] Required. - :type body: ~client.naming.main.models.ClientNameModel or JSON or IO[bytes] + :param body: Is either a ClientNameModel type or a IO[bytes] type. Required. + :type body: ~client.naming.main.models.ClientNameModel or + ~client.naming.main.types.ClientNameModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -307,11 +307,13 @@ def language( """ @overload - def language(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def language( + self, body: _types.LanguageClientNameModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """language. :param body: Required. - :type body: JSON + :type body: ~client.naming.main.types.LanguageClientNameModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -336,12 +338,13 @@ def language(self, body: IO[bytes], *, content_type: str = "application/json", * @distributed_trace def language( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.LanguageClientNameModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.LanguageClientNameModel, _types.LanguageClientNameModel, IO[bytes]], **kwargs: Any ) -> None: """language. - :param body: Is one of the following types: LanguageClientNameModel, JSON, IO[bytes] Required. - :type body: ~client.naming.main.models.LanguageClientNameModel or JSON or IO[bytes] + :param body: Is either a LanguageClientNameModel type or a IO[bytes] type. Required. + :type body: ~client.naming.main.models.LanguageClientNameModel or + ~client.naming.main.types.LanguageClientNameModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -410,12 +413,12 @@ def compatible_with_encoded_name( @overload def compatible_with_encoded_name( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ClientNameAndJsonEncodedNameModel, *, content_type: str = "application/json", **kwargs: Any ) -> None: """compatible_with_encoded_name. :param body: Required. - :type body: JSON + :type body: ~client.naming.main.types.ClientNameAndJsonEncodedNameModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -442,13 +445,15 @@ def compatible_with_encoded_name( @distributed_trace def compatible_with_encoded_name( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ClientNameAndJsonEncodedNameModel, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ClientNameAndJsonEncodedNameModel, _types.ClientNameAndJsonEncodedNameModel, IO[bytes]], + **kwargs: Any ) -> None: """compatible_with_encoded_name. - :param body: Is one of the following types: ClientNameAndJsonEncodedNameModel, JSON, IO[bytes] - Required. - :type body: ~client.naming.main.models.ClientNameAndJsonEncodedNameModel or JSON or IO[bytes] + :param body: Is either a ClientNameAndJsonEncodedNameModel type or a IO[bytes] type. Required. + :type body: ~client.naming.main.models.ClientNameAndJsonEncodedNameModel or + ~client.naming.main.types.ClientNameAndJsonEncodedNameModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -644,11 +649,11 @@ def client(self, body: _models.ClientModel, *, content_type: str = "application/ """ @overload - def client(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def client(self, body: _types.ClientModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """client. :param body: Required. - :type body: JSON + :type body: ~client.naming.main.types.ClientModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -673,12 +678,13 @@ def client(self, body: IO[bytes], *, content_type: str = "application/json", **k @distributed_trace def client( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ClientModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ClientModel, _types.ClientModel, IO[bytes]], **kwargs: Any ) -> None: """client. - :param body: Is one of the following types: ClientModel, JSON, IO[bytes] Required. - :type body: ~client.naming.main.models.ClientModel or JSON or IO[bytes] + :param body: Is either a ClientModel type or a IO[bytes] type. Required. + :type body: ~client.naming.main.models.ClientModel or ~client.naming.main.types.ClientModel or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -744,11 +750,11 @@ def language(self, body: _models.PythonModel, *, content_type: str = "applicatio """ @overload - def language(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def language(self, body: _types.PythonModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """language. :param body: Required. - :type body: JSON + :type body: ~client.naming.main.types.PythonModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -773,12 +779,13 @@ def language(self, body: IO[bytes], *, content_type: str = "application/json", * @distributed_trace def language( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PythonModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.PythonModel, _types.PythonModel, IO[bytes]], **kwargs: Any ) -> None: """language. - :param body: Is one of the following types: PythonModel, JSON, IO[bytes] Required. - :type body: ~client.naming.main.models.PythonModel or JSON or IO[bytes] + :param body: Is either a PythonModel type or a IO[bytes] type. Required. + :type body: ~client.naming.main.models.PythonModel or ~client.naming.main.types.PythonModel or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/client/naming/main/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/pyproject.toml index d5aa59086657..da2adfa3d4cc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-naming/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/types.py deleted file mode 100644 index 6eb530279947..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/client/overload/types.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing_extensions import Required, TypedDict - - -class Resource(TypedDict, total=False): - """Resource. - - :ivar id: Required. - :vartype id: str - :ivar name: Required. - :vartype name: str - :ivar scope: Required. - :vartype scope: str - """ - - id: Required[str] - """Required.""" - name: Required[str] - """Required.""" - scope: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/pyproject.toml index ea1f60dbdc58..8c9958bbb0ce 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-overload/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_operations/__init__.py deleted file mode 100644 index d15db16e70ef..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_operations/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._operations import _FirstClientOperationsMixin # type: ignore # pylint: disable=unused-import -from ._operations import _SecondClientOperationsMixin # type: ignore # pylint: disable=unused-import - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_operations/_operations.py deleted file mode 100644 index 62c6ce3e23b7..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_operations/_operations.py +++ /dev/null @@ -1,352 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace - -from .._configuration import FirstClientConfiguration, SecondClientConfiguration -from .._utils.serialization import Serializer -from .._utils.utils import ClientMixinABC - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_first_one_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/one" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_first_two_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/two" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_first_three_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/three" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_first_four_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/four" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_second_five_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/five" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_second_six_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/six" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -class _FirstClientOperationsMixin(ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], FirstClientConfiguration]): - - @distributed_trace - def one(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """one. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_first_one_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def two(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """two. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_first_two_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def three(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """three. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_first_three_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def four(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """four. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_first_four_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class _SecondClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SecondClientConfiguration] -): - - @distributed_trace - def five(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """five. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_second_five_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def six(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """six. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_second_six_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_operations/_operations.py deleted file mode 100644 index d756685ca5db..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_operations/_operations.py +++ /dev/null @@ -1,317 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async - -from ..._operations._operations import ( - build_first_four_request, - build_first_one_request, - build_first_three_request, - build_first_two_request, - build_second_five_request, - build_second_six_request, -) -from ..._utils.utils import ClientMixinABC -from .._configuration import FirstClientConfiguration, SecondClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class _FirstClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], FirstClientConfiguration] -): - - @distributed_trace_async - async def one(self, **kwargs: Any) -> None: - """one. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_first_one_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def two(self, **kwargs: Any) -> None: - """two. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_first_two_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def three(self, **kwargs: Any) -> None: - """three. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_first_three_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def four(self, **kwargs: Any) -> None: - """four. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_first_four_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class _SecondClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SecondClientConfiguration] -): - - @distributed_trace_async - async def five(self, **kwargs: Any) -> None: - """five. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_second_five_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def six(self, **kwargs: Any) -> None: - """six. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_second_six_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/client/structure/clientoperationgroup/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/pyproject.toml index f4b203cdf3dc..f09a91948d15 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-clientoperationgroup/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/client/structure/service/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/pyproject.toml index a8a068e338b5..acdbdf82a70d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-default/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/client/structure/multiclient/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/pyproject.toml index 361f3f0b3438..bcf92fd5a230 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-multiclient/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_operations/_operations.py deleted file mode 100644 index 7cd9b30af589..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_operations/_operations.py +++ /dev/null @@ -1,349 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace - -from .._configuration import RenamedOperationClientConfiguration -from .._utils.serialization import Serializer -from .._utils.utils import ClientMixinABC - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_renamed_operation_renamed_one_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - # Construct URL - _url = "/one" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_renamed_operation_renamed_three_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - # Construct URL - _url = "/three" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_renamed_operation_renamed_five_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - # Construct URL - _url = "/five" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_renamed_operation_renamed_two_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - # Construct URL - _url = "/two" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_renamed_operation_renamed_four_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - # Construct URL - _url = "/four" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_renamed_operation_renamed_six_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - # Construct URL - _url = "/six" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -class _RenamedOperationClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], RenamedOperationClientConfiguration] -): - - @distributed_trace - def renamed_one(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """renamed_one. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_one_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def renamed_three(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """renamed_three. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_three_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def renamed_five(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """renamed_five. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_five_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def renamed_two(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """renamed_two. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_two_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def renamed_four(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """renamed_four. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_four_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def renamed_six(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """renamed_six. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_six_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_operations/_operations.py deleted file mode 100644 index 42128333db4f..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_operations/_operations.py +++ /dev/null @@ -1,312 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async - -from ..._operations._operations import ( - build_renamed_operation_renamed_five_request, - build_renamed_operation_renamed_four_request, - build_renamed_operation_renamed_one_request, - build_renamed_operation_renamed_six_request, - build_renamed_operation_renamed_three_request, - build_renamed_operation_renamed_two_request, -) -from ..._utils.utils import ClientMixinABC -from .._configuration import RenamedOperationClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class _RenamedOperationClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], RenamedOperationClientConfiguration] -): - - @distributed_trace_async - async def renamed_one(self, **kwargs: Any) -> None: - """renamed_one. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_one_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def renamed_three(self, **kwargs: Any) -> None: - """renamed_three. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_three_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def renamed_five(self, **kwargs: Any) -> None: - """renamed_five. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_five_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def renamed_two(self, **kwargs: Any) -> None: - """renamed_two. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_two_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def renamed_four(self, **kwargs: Any) -> None: - """renamed_four. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_four_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def renamed_six(self, **kwargs: Any) -> None: - """renamed_six. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renamed_operation_renamed_six_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/pyproject.toml index 3d164b720e53..20626720375e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_operations/_operations.py deleted file mode 100644 index abb9a36f30ba..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_operations/_operations.py +++ /dev/null @@ -1,349 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace - -from .._configuration import TwoOperationGroupClientConfiguration -from .._utils.serialization import Serializer -from .._utils.utils import ClientMixinABC - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_two_operation_group_one_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/one" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_two_operation_group_three_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/three" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_two_operation_group_four_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/four" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_two_operation_group_two_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/two" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_two_operation_group_five_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/five" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -def build_two_operation_group_six_request(**kwargs: Any) -> HttpRequest: - # Construct URL - _url = "/six" - - return HttpRequest(method="POST", url=_url, **kwargs) - - -class _TwoOperationGroupClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], TwoOperationGroupClientConfiguration] -): - - @distributed_trace - def one(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """one. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_one_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def three(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """three. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_three_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def four(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """four. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_four_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def two(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """two. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_two_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def five(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """five. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_five_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def six(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """six. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_six_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_operations/_patch.py deleted file mode 100644 index ea765788358a..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_operations/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/utils.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/utils.py deleted file mode 100644 index 35c9c836f85f..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/_utils/utils.py +++ /dev/null @@ -1,25 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import Generic, TYPE_CHECKING, TypeVar - -if TYPE_CHECKING: - from .serialization import Deserializer, Serializer - - -TClient = TypeVar("TClient") -TConfig = TypeVar("TConfig") - - -class ClientMixinABC(ABC, Generic[TClient, TConfig]): - """DO NOT use this class. It is for internal typing use only.""" - - _client: TClient - _config: TConfig - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_operations/_operations.py deleted file mode 100644 index 4715cf0ad39e..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_operations/_operations.py +++ /dev/null @@ -1,312 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async - -from ..._operations._operations import ( - build_two_operation_group_five_request, - build_two_operation_group_four_request, - build_two_operation_group_one_request, - build_two_operation_group_six_request, - build_two_operation_group_three_request, - build_two_operation_group_two_request, -) -from ..._utils.utils import ClientMixinABC -from .._configuration import TwoOperationGroupClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class _TwoOperationGroupClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], TwoOperationGroupClientConfiguration] -): - - @distributed_trace_async - async def one(self, **kwargs: Any) -> None: - """one. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_one_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def three(self, **kwargs: Any) -> None: - """three. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_three_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def four(self, **kwargs: Any) -> None: - """four. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_four_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def two(self, **kwargs: Any) -> None: - """two. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_two_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def five(self, **kwargs: Any) -> None: - """five. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_five_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def six(self, **kwargs: Any) -> None: - """six. - - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_two_operation_group_six_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - "client": self._serialize.url("self._config.client", self._config.client, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_operations/_patch.py deleted file mode 100644 index ea765788358a..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_operations/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/client/structure/twooperationgroup/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/generated_tests/test_two_operation_group.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/generated_tests/test_two_operation_group.py deleted file mode 100644 index af87d5cf3cc4..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/generated_tests/test_two_operation_group.py +++ /dev/null @@ -1,67 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from devtools_testutils import recorded_by_proxy -from testpreparer import TwoOperationGroupClientTestBase, TwoOperationGroupPreparer - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestTwoOperationGroup(TwoOperationGroupClientTestBase): - @TwoOperationGroupPreparer() - @recorded_by_proxy - def test_one(self, twooperationgroup_endpoint): - client = self.create_client(endpoint=twooperationgroup_endpoint) - response = client.one() - - # please add some check logic here by yourself - # ... - - @TwoOperationGroupPreparer() - @recorded_by_proxy - def test_three(self, twooperationgroup_endpoint): - client = self.create_client(endpoint=twooperationgroup_endpoint) - response = client.three() - - # please add some check logic here by yourself - # ... - - @TwoOperationGroupPreparer() - @recorded_by_proxy - def test_four(self, twooperationgroup_endpoint): - client = self.create_client(endpoint=twooperationgroup_endpoint) - response = client.four() - - # please add some check logic here by yourself - # ... - - @TwoOperationGroupPreparer() - @recorded_by_proxy - def test_two(self, twooperationgroup_endpoint): - client = self.create_client(endpoint=twooperationgroup_endpoint) - response = client.two() - - # please add some check logic here by yourself - # ... - - @TwoOperationGroupPreparer() - @recorded_by_proxy - def test_five(self, twooperationgroup_endpoint): - client = self.create_client(endpoint=twooperationgroup_endpoint) - response = client.five() - - # please add some check logic here by yourself - # ... - - @TwoOperationGroupPreparer() - @recorded_by_proxy - def test_six(self, twooperationgroup_endpoint): - client = self.create_client(endpoint=twooperationgroup_endpoint) - response = client.six() - - # please add some check logic here by yourself - # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/generated_tests/test_two_operation_group_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/generated_tests/test_two_operation_group_async.py deleted file mode 100644 index a06484989511..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/generated_tests/test_two_operation_group_async.py +++ /dev/null @@ -1,68 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import pytest -from devtools_testutils.aio import recorded_by_proxy_async -from testpreparer import TwoOperationGroupPreparer -from testpreparer_async import TwoOperationGroupClientTestBaseAsync - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestTwoOperationGroupAsync(TwoOperationGroupClientTestBaseAsync): - @TwoOperationGroupPreparer() - @recorded_by_proxy_async - async def test_one(self, twooperationgroup_endpoint): - client = self.create_async_client(endpoint=twooperationgroup_endpoint) - response = await client.one() - - # please add some check logic here by yourself - # ... - - @TwoOperationGroupPreparer() - @recorded_by_proxy_async - async def test_three(self, twooperationgroup_endpoint): - client = self.create_async_client(endpoint=twooperationgroup_endpoint) - response = await client.three() - - # please add some check logic here by yourself - # ... - - @TwoOperationGroupPreparer() - @recorded_by_proxy_async - async def test_four(self, twooperationgroup_endpoint): - client = self.create_async_client(endpoint=twooperationgroup_endpoint) - response = await client.four() - - # please add some check logic here by yourself - # ... - - @TwoOperationGroupPreparer() - @recorded_by_proxy_async - async def test_two(self, twooperationgroup_endpoint): - client = self.create_async_client(endpoint=twooperationgroup_endpoint) - response = await client.two() - - # please add some check logic here by yourself - # ... - - @TwoOperationGroupPreparer() - @recorded_by_proxy_async - async def test_five(self, twooperationgroup_endpoint): - client = self.create_async_client(endpoint=twooperationgroup_endpoint) - response = await client.five() - - # please add some check logic here by yourself - # ... - - @TwoOperationGroupPreparer() - @recorded_by_proxy_async - async def test_six(self, twooperationgroup_endpoint): - client = self.create_async_client(endpoint=twooperationgroup_endpoint) - response = await client.six() - - # please add some check logic here by yourself - # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/pyproject.toml index 0721a0ca1131..a5a6aac7be62 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-twooperationgroup/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/aio/operations/_operations.py index c6f71e971477..a0a3bf39cf2f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from .... import models as _models3 +from .... import models as _models3, types as _types_models3 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import ArrayClientConfiguration @@ -46,7 +46,6 @@ build_property_space_delimited_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -87,12 +86,12 @@ async def comma_delimited( @overload async def comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.CommaDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.CommaDelimitedArrayProperty: """comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -121,13 +120,15 @@ async def comma_delimited( @distributed_trace_async async def comma_delimited( - self, body: Union[_models3.CommaDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.CommaDelimitedArrayProperty, _types_models3.CommaDelimitedArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models3.CommaDelimitedArrayProperty: """comma_delimited. - :param body: Is one of the following types: CommaDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.CommaDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.CommaDelimitedArrayProperty or + ~encode.array.types.CommaDelimitedArrayProperty or IO[bytes] :return: CommaDelimitedArrayProperty. The CommaDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedArrayProperty @@ -211,12 +212,12 @@ async def space_delimited( @overload async def space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.SpaceDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.SpaceDelimitedArrayProperty: """space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -245,13 +246,15 @@ async def space_delimited( @distributed_trace_async async def space_delimited( - self, body: Union[_models3.SpaceDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.SpaceDelimitedArrayProperty, _types_models3.SpaceDelimitedArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models3.SpaceDelimitedArrayProperty: """space_delimited. - :param body: Is one of the following types: SpaceDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.SpaceDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.SpaceDelimitedArrayProperty or + ~encode.array.types.SpaceDelimitedArrayProperty or IO[bytes] :return: SpaceDelimitedArrayProperty. The SpaceDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedArrayProperty @@ -335,12 +338,12 @@ async def pipe_delimited( @overload async def pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.PipeDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.PipeDelimitedArrayProperty: """pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -369,13 +372,15 @@ async def pipe_delimited( @distributed_trace_async async def pipe_delimited( - self, body: Union[_models3.PipeDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.PipeDelimitedArrayProperty, _types_models3.PipeDelimitedArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models3.PipeDelimitedArrayProperty: """pipe_delimited. - :param body: Is one of the following types: PipeDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.PipeDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.PipeDelimitedArrayProperty or + ~encode.array.types.PipeDelimitedArrayProperty or IO[bytes] :return: PipeDelimitedArrayProperty. The PipeDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedArrayProperty @@ -459,12 +464,16 @@ async def newline_delimited( @overload async def newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.NewlineDelimitedArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.NewlineDelimitedArrayProperty: """newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -493,13 +502,15 @@ async def newline_delimited( @distributed_trace_async async def newline_delimited( - self, body: Union[_models3.NewlineDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.NewlineDelimitedArrayProperty, _types_models3.NewlineDelimitedArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models3.NewlineDelimitedArrayProperty: """newline_delimited. - :param body: Is one of the following types: NewlineDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.NewlineDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a NewlineDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.NewlineDelimitedArrayProperty or + ~encode.array.types.NewlineDelimitedArrayProperty or IO[bytes] :return: NewlineDelimitedArrayProperty. The NewlineDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedArrayProperty @@ -583,12 +594,16 @@ async def enum_comma_delimited( @overload async def enum_comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.CommaDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.CommaDelimitedEnumArrayProperty: """enum_comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -617,13 +632,17 @@ async def enum_comma_delimited( @distributed_trace_async async def enum_comma_delimited( - self, body: Union[_models3.CommaDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.CommaDelimitedEnumArrayProperty, _types_models3.CommaDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any ) -> _models3.CommaDelimitedEnumArrayProperty: """enum_comma_delimited. - :param body: Is one of the following types: CommaDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.CommaDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.CommaDelimitedEnumArrayProperty or + ~encode.array.types.CommaDelimitedEnumArrayProperty or IO[bytes] :return: CommaDelimitedEnumArrayProperty. The CommaDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedEnumArrayProperty @@ -707,12 +726,16 @@ async def enum_space_delimited( @overload async def enum_space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.SpaceDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.SpaceDelimitedEnumArrayProperty: """enum_space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -741,13 +764,17 @@ async def enum_space_delimited( @distributed_trace_async async def enum_space_delimited( - self, body: Union[_models3.SpaceDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.SpaceDelimitedEnumArrayProperty, _types_models3.SpaceDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any ) -> _models3.SpaceDelimitedEnumArrayProperty: """enum_space_delimited. - :param body: Is one of the following types: SpaceDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.SpaceDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.SpaceDelimitedEnumArrayProperty or + ~encode.array.types.SpaceDelimitedEnumArrayProperty or IO[bytes] :return: SpaceDelimitedEnumArrayProperty. The SpaceDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedEnumArrayProperty @@ -831,12 +858,16 @@ async def enum_pipe_delimited( @overload async def enum_pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.PipeDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.PipeDelimitedEnumArrayProperty: """enum_pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -865,13 +896,15 @@ async def enum_pipe_delimited( @distributed_trace_async async def enum_pipe_delimited( - self, body: Union[_models3.PipeDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.PipeDelimitedEnumArrayProperty, _types_models3.PipeDelimitedEnumArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models3.PipeDelimitedEnumArrayProperty: """enum_pipe_delimited. - :param body: Is one of the following types: PipeDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.PipeDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.PipeDelimitedEnumArrayProperty or + ~encode.array.types.PipeDelimitedEnumArrayProperty or IO[bytes] :return: PipeDelimitedEnumArrayProperty. The PipeDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedEnumArrayProperty @@ -955,12 +988,16 @@ async def enum_newline_delimited( @overload async def enum_newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.NewlineDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.NewlineDelimitedEnumArrayProperty: """enum_newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -989,13 +1026,17 @@ async def enum_newline_delimited( @distributed_trace_async async def enum_newline_delimited( - self, body: Union[_models3.NewlineDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.NewlineDelimitedEnumArrayProperty, _types_models3.NewlineDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any ) -> _models3.NewlineDelimitedEnumArrayProperty: """enum_newline_delimited. - :param body: Is one of the following types: NewlineDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.NewlineDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a NewlineDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.NewlineDelimitedEnumArrayProperty or + ~encode.array.types.NewlineDelimitedEnumArrayProperty or IO[bytes] :return: NewlineDelimitedEnumArrayProperty. The NewlineDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedEnumArrayProperty @@ -1083,12 +1124,16 @@ async def extensible_enum_comma_delimited( @overload async def extensible_enum_comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.CommaDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.CommaDelimitedExtensibleEnumArrayProperty: """extensible_enum_comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1117,13 +1162,20 @@ async def extensible_enum_comma_delimited( @distributed_trace_async async def extensible_enum_comma_delimited( - self, body: Union[_models3.CommaDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.CommaDelimitedExtensibleEnumArrayProperty, + _types_models3.CommaDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models3.CommaDelimitedExtensibleEnumArrayProperty: """extensible_enum_comma_delimited. - :param body: Is one of the following types: CommaDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.CommaDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: CommaDelimitedExtensibleEnumArrayProperty. The CommaDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty @@ -1211,12 +1263,16 @@ async def extensible_enum_space_delimited( @overload async def extensible_enum_space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.SpaceDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.SpaceDelimitedExtensibleEnumArrayProperty: """extensible_enum_space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1245,13 +1301,20 @@ async def extensible_enum_space_delimited( @distributed_trace_async async def extensible_enum_space_delimited( - self, body: Union[_models3.SpaceDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.SpaceDelimitedExtensibleEnumArrayProperty, + _types_models3.SpaceDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models3.SpaceDelimitedExtensibleEnumArrayProperty: """extensible_enum_space_delimited. - :param body: Is one of the following types: SpaceDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.SpaceDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: SpaceDelimitedExtensibleEnumArrayProperty. The SpaceDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty @@ -1339,12 +1402,16 @@ async def extensible_enum_pipe_delimited( @overload async def extensible_enum_pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.PipeDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.PipeDelimitedExtensibleEnumArrayProperty: """extensible_enum_pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1373,13 +1440,20 @@ async def extensible_enum_pipe_delimited( @distributed_trace_async async def extensible_enum_pipe_delimited( - self, body: Union[_models3.PipeDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.PipeDelimitedExtensibleEnumArrayProperty, + _types_models3.PipeDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models3.PipeDelimitedExtensibleEnumArrayProperty: """extensible_enum_pipe_delimited. - :param body: Is one of the following types: PipeDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.PipeDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: PipeDelimitedExtensibleEnumArrayProperty. The PipeDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty @@ -1467,12 +1541,16 @@ async def extensible_enum_newline_delimited( @overload async def extensible_enum_newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.NewlineDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.NewlineDelimitedExtensibleEnumArrayProperty: """extensible_enum_newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1501,14 +1579,20 @@ async def extensible_enum_newline_delimited( @distributed_trace_async async def extensible_enum_newline_delimited( - self, body: Union[_models3.NewlineDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.NewlineDelimitedExtensibleEnumArrayProperty, + _types_models3.NewlineDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models3.NewlineDelimitedExtensibleEnumArrayProperty: """extensible_enum_newline_delimited. - :param body: Is one of the following types: NewlineDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty or JSON or - IO[bytes] + :param body: Is either a NewlineDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.NewlineDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: NewlineDelimitedExtensibleEnumArrayProperty. The NewlineDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/operations/_operations.py index b5ef7b0ad66c..326fad11c0af 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/operations/_operations.py @@ -27,12 +27,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..._configuration import ArrayClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -288,12 +287,12 @@ def comma_delimited( @overload def comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.CommaDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.CommaDelimitedArrayProperty: """comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -322,13 +321,15 @@ def comma_delimited( @distributed_trace def comma_delimited( - self, body: Union[_models2.CommaDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.CommaDelimitedArrayProperty, _types_models2.CommaDelimitedArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models2.CommaDelimitedArrayProperty: """comma_delimited. - :param body: Is one of the following types: CommaDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.CommaDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.CommaDelimitedArrayProperty or + ~encode.array.types.CommaDelimitedArrayProperty or IO[bytes] :return: CommaDelimitedArrayProperty. The CommaDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedArrayProperty @@ -412,12 +413,12 @@ def space_delimited( @overload def space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.SpaceDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.SpaceDelimitedArrayProperty: """space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -446,13 +447,15 @@ def space_delimited( @distributed_trace def space_delimited( - self, body: Union[_models2.SpaceDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.SpaceDelimitedArrayProperty, _types_models2.SpaceDelimitedArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models2.SpaceDelimitedArrayProperty: """space_delimited. - :param body: Is one of the following types: SpaceDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.SpaceDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.SpaceDelimitedArrayProperty or + ~encode.array.types.SpaceDelimitedArrayProperty or IO[bytes] :return: SpaceDelimitedArrayProperty. The SpaceDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedArrayProperty @@ -536,12 +539,12 @@ def pipe_delimited( @overload def pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.PipeDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.PipeDelimitedArrayProperty: """pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -570,13 +573,15 @@ def pipe_delimited( @distributed_trace def pipe_delimited( - self, body: Union[_models2.PipeDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.PipeDelimitedArrayProperty, _types_models2.PipeDelimitedArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models2.PipeDelimitedArrayProperty: """pipe_delimited. - :param body: Is one of the following types: PipeDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.PipeDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.PipeDelimitedArrayProperty or + ~encode.array.types.PipeDelimitedArrayProperty or IO[bytes] :return: PipeDelimitedArrayProperty. The PipeDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedArrayProperty @@ -660,12 +665,16 @@ def newline_delimited( @overload def newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.NewlineDelimitedArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.NewlineDelimitedArrayProperty: """newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -694,13 +703,15 @@ def newline_delimited( @distributed_trace def newline_delimited( - self, body: Union[_models2.NewlineDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.NewlineDelimitedArrayProperty, _types_models2.NewlineDelimitedArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models2.NewlineDelimitedArrayProperty: """newline_delimited. - :param body: Is one of the following types: NewlineDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.NewlineDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a NewlineDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.NewlineDelimitedArrayProperty or + ~encode.array.types.NewlineDelimitedArrayProperty or IO[bytes] :return: NewlineDelimitedArrayProperty. The NewlineDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedArrayProperty @@ -784,12 +795,16 @@ def enum_comma_delimited( @overload def enum_comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.CommaDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.CommaDelimitedEnumArrayProperty: """enum_comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -818,13 +833,17 @@ def enum_comma_delimited( @distributed_trace def enum_comma_delimited( - self, body: Union[_models2.CommaDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.CommaDelimitedEnumArrayProperty, _types_models2.CommaDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models2.CommaDelimitedEnumArrayProperty: """enum_comma_delimited. - :param body: Is one of the following types: CommaDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.CommaDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.CommaDelimitedEnumArrayProperty or + ~encode.array.types.CommaDelimitedEnumArrayProperty or IO[bytes] :return: CommaDelimitedEnumArrayProperty. The CommaDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedEnumArrayProperty @@ -908,12 +927,16 @@ def enum_space_delimited( @overload def enum_space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.SpaceDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.SpaceDelimitedEnumArrayProperty: """enum_space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -942,13 +965,17 @@ def enum_space_delimited( @distributed_trace def enum_space_delimited( - self, body: Union[_models2.SpaceDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.SpaceDelimitedEnumArrayProperty, _types_models2.SpaceDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models2.SpaceDelimitedEnumArrayProperty: """enum_space_delimited. - :param body: Is one of the following types: SpaceDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.SpaceDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.SpaceDelimitedEnumArrayProperty or + ~encode.array.types.SpaceDelimitedEnumArrayProperty or IO[bytes] :return: SpaceDelimitedEnumArrayProperty. The SpaceDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedEnumArrayProperty @@ -1032,12 +1059,16 @@ def enum_pipe_delimited( @overload def enum_pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.PipeDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.PipeDelimitedEnumArrayProperty: """enum_pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1066,13 +1097,15 @@ def enum_pipe_delimited( @distributed_trace def enum_pipe_delimited( - self, body: Union[_models2.PipeDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.PipeDelimitedEnumArrayProperty, _types_models2.PipeDelimitedEnumArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models2.PipeDelimitedEnumArrayProperty: """enum_pipe_delimited. - :param body: Is one of the following types: PipeDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.PipeDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.PipeDelimitedEnumArrayProperty or + ~encode.array.types.PipeDelimitedEnumArrayProperty or IO[bytes] :return: PipeDelimitedEnumArrayProperty. The PipeDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedEnumArrayProperty @@ -1156,12 +1189,16 @@ def enum_newline_delimited( @overload def enum_newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.NewlineDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.NewlineDelimitedEnumArrayProperty: """enum_newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1190,13 +1227,17 @@ def enum_newline_delimited( @distributed_trace def enum_newline_delimited( - self, body: Union[_models2.NewlineDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.NewlineDelimitedEnumArrayProperty, _types_models2.NewlineDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models2.NewlineDelimitedEnumArrayProperty: """enum_newline_delimited. - :param body: Is one of the following types: NewlineDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.NewlineDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a NewlineDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.NewlineDelimitedEnumArrayProperty or + ~encode.array.types.NewlineDelimitedEnumArrayProperty or IO[bytes] :return: NewlineDelimitedEnumArrayProperty. The NewlineDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedEnumArrayProperty @@ -1284,12 +1325,16 @@ def extensible_enum_comma_delimited( @overload def extensible_enum_comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.CommaDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.CommaDelimitedExtensibleEnumArrayProperty: """extensible_enum_comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1318,13 +1363,20 @@ def extensible_enum_comma_delimited( @distributed_trace def extensible_enum_comma_delimited( - self, body: Union[_models2.CommaDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.CommaDelimitedExtensibleEnumArrayProperty, + _types_models2.CommaDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models2.CommaDelimitedExtensibleEnumArrayProperty: """extensible_enum_comma_delimited. - :param body: Is one of the following types: CommaDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.CommaDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: CommaDelimitedExtensibleEnumArrayProperty. The CommaDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty @@ -1412,12 +1464,16 @@ def extensible_enum_space_delimited( @overload def extensible_enum_space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.SpaceDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.SpaceDelimitedExtensibleEnumArrayProperty: """extensible_enum_space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1446,13 +1502,20 @@ def extensible_enum_space_delimited( @distributed_trace def extensible_enum_space_delimited( - self, body: Union[_models2.SpaceDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.SpaceDelimitedExtensibleEnumArrayProperty, + _types_models2.SpaceDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models2.SpaceDelimitedExtensibleEnumArrayProperty: """extensible_enum_space_delimited. - :param body: Is one of the following types: SpaceDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.SpaceDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: SpaceDelimitedExtensibleEnumArrayProperty. The SpaceDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty @@ -1540,12 +1603,16 @@ def extensible_enum_pipe_delimited( @overload def extensible_enum_pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.PipeDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.PipeDelimitedExtensibleEnumArrayProperty: """extensible_enum_pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1574,13 +1641,20 @@ def extensible_enum_pipe_delimited( @distributed_trace def extensible_enum_pipe_delimited( - self, body: Union[_models2.PipeDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.PipeDelimitedExtensibleEnumArrayProperty, + _types_models2.PipeDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models2.PipeDelimitedExtensibleEnumArrayProperty: """extensible_enum_pipe_delimited. - :param body: Is one of the following types: PipeDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.PipeDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: PipeDelimitedExtensibleEnumArrayProperty. The PipeDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty @@ -1668,12 +1742,16 @@ def extensible_enum_newline_delimited( @overload def extensible_enum_newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.NewlineDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.NewlineDelimitedExtensibleEnumArrayProperty: """extensible_enum_newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1702,14 +1780,20 @@ def extensible_enum_newline_delimited( @distributed_trace def extensible_enum_newline_delimited( - self, body: Union[_models2.NewlineDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.NewlineDelimitedExtensibleEnumArrayProperty, + _types_models2.NewlineDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models2.NewlineDelimitedExtensibleEnumArrayProperty: """extensible_enum_newline_delimited. - :param body: Is one of the following types: NewlineDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty or JSON or - IO[bytes] + :param body: Is either a NewlineDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.NewlineDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: NewlineDelimitedExtensibleEnumArrayProperty. The NewlineDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/property/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/types.py index f5a079fa935a..20d6c6a8d1b0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/encode/array/types.py @@ -28,7 +28,7 @@ class CommaDelimitedEnumArrayProperty(TypedDict, total=False): """CommaDelimitedEnumArrayProperty. :ivar value: Required. - :vartype value: list[str or ~encode.array.models.Colors] + :vartype value: list[Union[str, "Colors"]] """ value: Required[list[Union[str, "Colors"]]] @@ -39,7 +39,7 @@ class CommaDelimitedExtensibleEnumArrayProperty(TypedDict, total=False): # pyli """CommaDelimitedExtensibleEnumArrayProperty. :ivar value: Required. - :vartype value: list[str or ~encode.array.models.ColorsExtensibleEnum] + :vartype value: list[Union[str, "ColorsExtensibleEnum"]] """ value: Required[list[Union[str, "ColorsExtensibleEnum"]]] @@ -61,7 +61,7 @@ class NewlineDelimitedEnumArrayProperty(TypedDict, total=False): """NewlineDelimitedEnumArrayProperty. :ivar value: Required. - :vartype value: list[str or ~encode.array.models.Colors] + :vartype value: list[Union[str, "Colors"]] """ value: Required[list[Union[str, "Colors"]]] @@ -72,7 +72,7 @@ class NewlineDelimitedExtensibleEnumArrayProperty(TypedDict, total=False): # py """NewlineDelimitedExtensibleEnumArrayProperty. :ivar value: Required. - :vartype value: list[str or ~encode.array.models.ColorsExtensibleEnum] + :vartype value: list[Union[str, "ColorsExtensibleEnum"]] """ value: Required[list[Union[str, "ColorsExtensibleEnum"]]] @@ -94,7 +94,7 @@ class PipeDelimitedEnumArrayProperty(TypedDict, total=False): """PipeDelimitedEnumArrayProperty. :ivar value: Required. - :vartype value: list[str or ~encode.array.models.Colors] + :vartype value: list[Union[str, "Colors"]] """ value: Required[list[Union[str, "Colors"]]] @@ -105,7 +105,7 @@ class PipeDelimitedExtensibleEnumArrayProperty(TypedDict, total=False): """PipeDelimitedExtensibleEnumArrayProperty. :ivar value: Required. - :vartype value: list[str or ~encode.array.models.ColorsExtensibleEnum] + :vartype value: list[Union[str, "ColorsExtensibleEnum"]] """ value: Required[list[Union[str, "ColorsExtensibleEnum"]]] @@ -127,7 +127,7 @@ class SpaceDelimitedEnumArrayProperty(TypedDict, total=False): """SpaceDelimitedEnumArrayProperty. :ivar value: Required. - :vartype value: list[str or ~encode.array.models.Colors] + :vartype value: list[Union[str, "Colors"]] """ value: Required[list[Union[str, "Colors"]]] @@ -138,7 +138,7 @@ class SpaceDelimitedExtensibleEnumArrayProperty(TypedDict, total=False): # pyli """SpaceDelimitedExtensibleEnumArrayProperty. :ivar value: Required. - :vartype value: list[str or ~encode.array.models.ColorsExtensibleEnum] + :vartype value: list[Union[str, "ColorsExtensibleEnum"]] """ value: Required[list[Union[str, "ColorsExtensibleEnum"]]] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/pyproject.toml index 657d70b808d2..2eea036dec0d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-array/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/CHANGELOG.md new file mode 100644 index 000000000000..b957b2575b48 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (1970-01-01) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/LICENSE b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/MANIFEST.in b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/MANIFEST.in new file mode 100644 index 000000000000..882a33f4952b --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/MANIFEST.in @@ -0,0 +1,6 @@ +include *.md +include LICENSE +include encode/boolean/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include encode/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/README.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/_metadata.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/_metadata.json new file mode 100644 index 000000000000..49515fdbafdf --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/_metadata.json @@ -0,0 +1,3 @@ +{ + "apiVersions": {} +} \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/apiview-properties.json new file mode 100644 index 000000000000..2bac99383911 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/apiview-properties.json @@ -0,0 +1,15 @@ +{ + "CrossLanguagePackageId": "Encode.Boolean", + "CrossLanguageDefinitionId": { + "encode.boolean.property.models.BoolAsStringProperty": "Encode.Boolean.Property.BoolAsStringProperty", + "encode.boolean.operations.PropertyOperations.true_lower": "Encode.Boolean.Property.trueLower", + "encode.boolean.aio.operations.PropertyOperations.true_lower": "Encode.Boolean.Property.trueLower", + "encode.boolean.operations.PropertyOperations.false_lower": "Encode.Boolean.Property.falseLower", + "encode.boolean.aio.operations.PropertyOperations.false_lower": "Encode.Boolean.Property.falseLower", + "encode.boolean.operations.PropertyOperations.true_upper": "Encode.Boolean.Property.trueUpper", + "encode.boolean.aio.operations.PropertyOperations.true_upper": "Encode.Boolean.Property.trueUpper", + "encode.boolean.operations.PropertyOperations.false_mixed": "Encode.Boolean.Property.falseMixed", + "encode.boolean.aio.operations.PropertyOperations.false_mixed": "Encode.Boolean.Property.falseMixed" + }, + "CrossLanguageVersion": "774ecf75d81f" +} \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/dev_requirements.txt b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/dev_requirements.txt new file mode 100644 index 000000000000..0e53b6a72db5 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/dev_requirements.txt @@ -0,0 +1,3 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +aiohttp \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/__init__.py new file mode 100644 index 000000000000..140c39352dc1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import BooleanClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BooleanClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_client.py new file mode 100644 index 000000000000..a800bf13220d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_client.py @@ -0,0 +1,100 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +import sys +from typing import Any + +from azure.core import PipelineClient +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse + +from ._configuration import BooleanClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .property.operations import PropertyOperations + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + + +class BooleanClient: # pylint: disable=client-accepts-api-version-keyword + """Test for encode decorator on boolean. + + :ivar property: PropertyOperations operations + :vartype property: encode.boolean.operations.PropertyOperations + :keyword endpoint: Service host. Default value is "http://localhost:3000". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "http://localhost:3000", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = BooleanClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.property = PropertyOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_configuration.py new file mode 100644 index 000000000000..0d44dc16e9f6 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_configuration.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any + +from azure.core.pipeline import policies + +from ._version import VERSION + + +class BooleanClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for BooleanClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "http://localhost:3000". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "encode-boolean/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_utils/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_utils/model_base.py new file mode 100644 index 000000000000..0f2c5bdfe70f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_utils/model_base.py @@ -0,0 +1,1771 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null + +from azure.core.rest import HttpResponse + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on the mapping's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on the mapping's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: a set-like object providing a view on the mapping's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: The value for key if key is in the dictionary, else default. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if the dictionary is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from the dictionary. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Update the dictionary from a mapping or an iterable of key-value pairs. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: The value for key if key is in the dictionary, else default. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _serialize_duration(o, format) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass: dict[str, typing.Any] = {} + if args: + if isinstance(args[0], ET.Element): + dict_to_pass.update(self._init_from_xml(args[0])) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) + super().__init__(dict_to_pass) + + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + self, element: ET.Element + ) -> dict[str, typing.Any]: + """Deserialize an XML element into a dict mapping rest field names to values. + + :param ET.Element element: The XML element to deserialize from. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + existed_attr_keys: list[str] = [] + + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value.text if isinstance(value, ET.Element) else value) + except ValueError: + # for unknown value, return raw value + return value.text if isinstance(value, ET.Element) else value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +# pylint: disable=too-many-instance-attributes +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._is_optional = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + self._deserializer = deserializer + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + deserializer=deserializer, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) + wrapped_element = _create_xml_element( + element_name, + model_meta.get("prefix"), + _model_ns, + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + _set_xml_attribute(wrapped_element, k, v, prop_meta) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": _dict_ns, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": _items_ns, + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + _safe_register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_utils/serialization.py new file mode 100644 index 000000000000..75906e2eb77f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_utils/serialization.py @@ -0,0 +1,2175 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_version.py similarity index 89% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_types.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_version.py index d9eb2e02134b..be71c81bd282 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/_version.py @@ -6,6 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Union - -UnionV2 = Union[str, float] +VERSION = "1.0.0b1" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/__init__.py new file mode 100644 index 000000000000..75f23e03d6e2 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import BooleanClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BooleanClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/_client.py new file mode 100644 index 000000000000..86eb29b553ae --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/_client.py @@ -0,0 +1,102 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +import sys +from typing import Any, Awaitable + +from azure.core import AsyncPipelineClient +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest + +from .._utils.serialization import Deserializer, Serializer +from ..property.aio.operations import PropertyOperations +from ._configuration import BooleanClientConfiguration + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + + +class BooleanClient: # pylint: disable=client-accepts-api-version-keyword + """Test for encode decorator on boolean. + + :ivar property: PropertyOperations operations + :vartype property: encode.boolean.aio.operations.PropertyOperations + :keyword endpoint: Service host. Default value is "http://localhost:3000". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "http://localhost:3000", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = BooleanClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.property = PropertyOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/_configuration.py new file mode 100644 index 000000000000..17afa57c8b7e --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/_configuration.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any + +from azure.core.pipeline import policies + +from .._version import VERSION + + +class BooleanClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for BooleanClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "http://localhost:3000". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "encode-boolean/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/operations/__init__.py new file mode 100644 index 000000000000..22f110740133 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import PropertyOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PropertyOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/operations/_operations.py new file mode 100644 index 000000000000..31113da278c3 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/operations/_operations.py @@ -0,0 +1,539 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models2, types as _types_models2 +from ...._utils.model_base import SdkJSONEncoder, _deserialize +from ...._utils.serialization import Deserializer, Serializer +from ....aio._configuration import BooleanClientConfiguration +from ...operations._operations import ( + build_property_false_lower_request, + build_property_false_mixed_request, + build_property_true_lower_request, + build_property_true_upper_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class PropertyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~encode.boolean.aio.BooleanClient`'s + :attr:`property` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: BooleanClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def true_lower( + self, value: _models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def true_lower( + self, value: _types_models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def true_lower( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def true_lower( + self, value: Union[_models2.BoolAsStringProperty, _types_models2.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_lower. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_true_lower_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models2.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def false_lower( + self, value: _models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def false_lower( + self, value: _types_models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def false_lower( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def false_lower( + self, value: Union[_models2.BoolAsStringProperty, _types_models2.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_lower. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_false_lower_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models2.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def true_upper( + self, value: _models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def true_upper( + self, value: _types_models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def true_upper( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def true_upper( + self, value: Union[_models2.BoolAsStringProperty, _types_models2.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_upper. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_true_upper_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models2.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def false_mixed( + self, value: _models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def false_mixed( + self, value: _types_models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def false_mixed( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def false_mixed( + self, value: Union[_models2.BoolAsStringProperty, _types_models2.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_mixed. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_false_mixed_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models2.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/models/__init__.py similarity index 88% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/models/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/models/__init__.py index 08806180ab50..20ce6ca17f34 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/models/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/models/__init__.py @@ -14,18 +14,14 @@ from ._models import ( # type: ignore - BlobProperties, - Input, - WithBodyRequest, + BoolAsStringProperty, ) from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "BlobProperties", - "Input", - "WithBodyRequest", + "BoolAsStringProperty", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/models/_models.py new file mode 100644 index 000000000000..547daabe47ec --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/models/_models.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +from typing import Any, Mapping, overload + +from ..._utils.model_base import Model as _Model, rest_field + + +class BoolAsStringProperty(_Model): + """BoolAsStringProperty. + + :ivar value: Required. + :vartype value: bool + """ + + value: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + value: bool, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/operations/__init__.py new file mode 100644 index 000000000000..22f110740133 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import PropertyOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PropertyOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/operations/_operations.py new file mode 100644 index 000000000000..3ec493b5ab49 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/operations/_operations.py @@ -0,0 +1,604 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models1, types as _types_models1 +from ..._configuration import BooleanClientConfiguration +from ..._utils.model_base import SdkJSONEncoder, _deserialize +from ..._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_property_true_lower_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/encode/boolean/property/true-lower" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_property_false_lower_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/encode/boolean/property/false-lower" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_property_true_upper_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/encode/boolean/property/true-upper" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_property_false_mixed_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/encode/boolean/property/false-mixed" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +class PropertyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~encode.boolean.BooleanClient`'s + :attr:`property` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: BooleanClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def true_lower( + self, value: _models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def true_lower( + self, value: _types_models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def true_lower( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def true_lower( + self, value: Union[_models1.BoolAsStringProperty, _types_models1.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_lower. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_true_lower_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models1.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def false_lower( + self, value: _models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def false_lower( + self, value: _types_models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def false_lower( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def false_lower( + self, value: Union[_models1.BoolAsStringProperty, _types_models1.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_lower. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_false_lower_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models1.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def true_upper( + self, value: _models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def true_upper( + self, value: _types_models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def true_upper( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def true_upper( + self, value: Union[_models1.BoolAsStringProperty, _types_models1.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_upper. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_true_upper_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models1.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def false_mixed( + self, value: _models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def false_mixed( + self, value: _types_models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def false_mixed( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def false_mixed( + self, value: Union[_models1.BoolAsStringProperty, _types_models1.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_mixed. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_false_mixed_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models1.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/types.py similarity index 77% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/types.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/types.py index 4633982a34d1..e3c0f169413d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/authentication-oauth2/authentication/oauth2/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/property/types.py @@ -9,12 +9,12 @@ from typing_extensions import Required, TypedDict -class InvalidAuth(TypedDict, total=False): - """InvalidAuth. +class BoolAsStringProperty(TypedDict, total=False): + """BoolAsStringProperty. - :ivar error: Required. - :vartype error: str + :ivar value: Required. + :vartype value: bool """ - error: Required[str] + value: Required[bool] """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/py.typed b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/encode/boolean/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/conftest.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/conftest.py new file mode 100644 index 000000000000..bd1eb81208c1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + boolean_subscription_id = os.environ.get("BOOLEAN_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + boolean_tenant_id = os.environ.get("BOOLEAN_TENANT_ID", "00000000-0000-0000-0000-000000000000") + boolean_client_id = os.environ.get("BOOLEAN_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + boolean_client_secret = os.environ.get("BOOLEAN_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=boolean_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=boolean_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=boolean_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=boolean_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/test_boolean_property_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/test_boolean_property_operations.py new file mode 100644 index 000000000000..9173c74ee3c8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/test_boolean_property_operations.py @@ -0,0 +1,57 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import BooleanClientTestBase, BooleanPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestBooleanPropertyOperations(BooleanClientTestBase): + @BooleanPreparer() + @recorded_by_proxy + def test_property_true_lower(self, boolean_endpoint): + client = self.create_client(endpoint=boolean_endpoint) + response = client.property.true_lower( + value={"value": bool}, + ) + + # please add some check logic here by yourself + # ... + + @BooleanPreparer() + @recorded_by_proxy + def test_property_false_lower(self, boolean_endpoint): + client = self.create_client(endpoint=boolean_endpoint) + response = client.property.false_lower( + value={"value": bool}, + ) + + # please add some check logic here by yourself + # ... + + @BooleanPreparer() + @recorded_by_proxy + def test_property_true_upper(self, boolean_endpoint): + client = self.create_client(endpoint=boolean_endpoint) + response = client.property.true_upper( + value={"value": bool}, + ) + + # please add some check logic here by yourself + # ... + + @BooleanPreparer() + @recorded_by_proxy + def test_property_false_mixed(self, boolean_endpoint): + client = self.create_client(endpoint=boolean_endpoint) + response = client.property.false_mixed( + value={"value": bool}, + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/test_boolean_property_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/test_boolean_property_operations_async.py new file mode 100644 index 000000000000..87fb50e37b77 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/test_boolean_property_operations_async.py @@ -0,0 +1,58 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import BooleanPreparer +from testpreparer_async import BooleanClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestBooleanPropertyOperationsAsync(BooleanClientTestBaseAsync): + @BooleanPreparer() + @recorded_by_proxy_async + async def test_property_true_lower(self, boolean_endpoint): + client = self.create_async_client(endpoint=boolean_endpoint) + response = await client.property.true_lower( + value={"value": bool}, + ) + + # please add some check logic here by yourself + # ... + + @BooleanPreparer() + @recorded_by_proxy_async + async def test_property_false_lower(self, boolean_endpoint): + client = self.create_async_client(endpoint=boolean_endpoint) + response = await client.property.false_lower( + value={"value": bool}, + ) + + # please add some check logic here by yourself + # ... + + @BooleanPreparer() + @recorded_by_proxy_async + async def test_property_true_upper(self, boolean_endpoint): + client = self.create_async_client(endpoint=boolean_endpoint) + response = await client.property.true_upper( + value={"value": bool}, + ) + + # please add some check logic here by yourself + # ... + + @BooleanPreparer() + @recorded_by_proxy_async + async def test_property_false_mixed(self, boolean_endpoint): + client = self.create_async_client(endpoint=boolean_endpoint) + response = await client.property.false_mixed( + value={"value": bool}, + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/testpreparer.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/testpreparer.py new file mode 100644 index 000000000000..63586c382b2f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/testpreparer.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer +from encode.boolean import BooleanClient +import functools + + +class BooleanClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(BooleanClient) + return self.create_client_from_credential( + BooleanClient, + credential=credential, + endpoint=endpoint, + ) + + +BooleanPreparer = functools.partial(PowerShellPreparer, "boolean", boolean_endpoint="https://fake_boolean_endpoint.com") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/testpreparer_async.py similarity index 52% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/types.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/testpreparer_async.py index f429ced602f9..86da9fb6e3a5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-deserialize-empty-string-as-null/specs/azure/clientgenerator/core/emptystring/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/generated_tests/testpreparer_async.py @@ -5,16 +5,16 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from devtools_testutils import AzureRecordedTestCase +from encode.boolean.aio import BooleanClient -from typing_extensions import Required, TypedDict +class BooleanClientTestBaseAsync(AzureRecordedTestCase): -class ResponseModel(TypedDict, total=False): - """This is a Model contains a string-like property of type url. - - :ivar sample_url: Required. - :vartype sample_url: str - """ - - sampleUrl: Required[str] - """Required.""" + def create_async_client(self, endpoint): + credential = self.get_credential(BooleanClient, is_async=True) + return self.create_client_from_credential( + BooleanClient, + credential=credential, + endpoint=endpoint, + ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/pyproject.toml new file mode 100644 index 000000000000..8b4704801d8c --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-boolean/pyproject.toml @@ -0,0 +1,60 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "encode-boolean" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Corporation Azure Encode Boolean Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", +] +requires-python = ">=3.10" +keywords = ["azure", "azure sdk"] + +dependencies = [ + "isodate>=0.6.1", + "azure-core>=1.37.0", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "encode.boolean._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "encode", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/header/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/header/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/header/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/header/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/header/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/header/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/header/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/header/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/aio/operations/_operations.py index e0c38f638595..9e272ef78feb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/aio/operations/_operations.py @@ -26,7 +26,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from .... import models as _models3 +from .... import models as _models3, types as _types_models3 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import BytesClientConfiguration @@ -37,7 +37,6 @@ build_property_default_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -77,12 +76,12 @@ async def default( @overload async def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.DefaultBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.DefaultBytesProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.DefaultBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -109,12 +108,13 @@ async def default( @distributed_trace_async async def default( - self, body: Union[_models3.DefaultBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models3.DefaultBytesProperty, _types_models3.DefaultBytesProperty, IO[bytes]], **kwargs: Any ) -> _models3.DefaultBytesProperty: """default. - :param body: Is one of the following types: DefaultBytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.DefaultBytesProperty or JSON or IO[bytes] + :param body: Is either a DefaultBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.DefaultBytesProperty or + ~encode.bytes.types.DefaultBytesProperty or IO[bytes] :return: DefaultBytesProperty. The DefaultBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.DefaultBytesProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -196,12 +196,12 @@ async def base64( @overload async def base64( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.Base64BytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.Base64BytesProperty: """base64. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -228,12 +228,13 @@ async def base64( @distributed_trace_async async def base64( - self, body: Union[_models3.Base64BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models3.Base64BytesProperty, _types_models3.Base64BytesProperty, IO[bytes]], **kwargs: Any ) -> _models3.Base64BytesProperty: """base64. - :param body: Is one of the following types: Base64BytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.Base64BytesProperty or JSON or IO[bytes] + :param body: Is either a Base64BytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64BytesProperty or ~encode.bytes.types.Base64BytesProperty + or IO[bytes] :return: Base64BytesProperty. The Base64BytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64BytesProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -315,12 +316,12 @@ async def base64_url( @overload async def base64_url( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.Base64urlBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.Base64urlBytesProperty: """base64_url. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64urlBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -347,12 +348,15 @@ async def base64_url( @distributed_trace_async async def base64_url( - self, body: Union[_models3.Base64urlBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.Base64urlBytesProperty, _types_models3.Base64urlBytesProperty, IO[bytes]], + **kwargs: Any ) -> _models3.Base64urlBytesProperty: """base64_url. - :param body: Is one of the following types: Base64urlBytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.Base64urlBytesProperty or JSON or IO[bytes] + :param body: Is either a Base64urlBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64urlBytesProperty or + ~encode.bytes.types.Base64urlBytesProperty or IO[bytes] :return: Base64urlBytesProperty. The Base64urlBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64urlBytesProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -435,12 +439,12 @@ async def base64_url_array( @overload async def base64_url_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.Base64urlArrayBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.Base64urlArrayBytesProperty: """base64_url_array. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64urlArrayBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -469,13 +473,15 @@ async def base64_url_array( @distributed_trace_async async def base64_url_array( - self, body: Union[_models3.Base64urlArrayBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.Base64urlArrayBytesProperty, _types_models3.Base64urlArrayBytesProperty, IO[bytes]], + **kwargs: Any ) -> _models3.Base64urlArrayBytesProperty: """base64_url_array. - :param body: Is one of the following types: Base64urlArrayBytesProperty, JSON, IO[bytes] - Required. - :type body: ~encode.bytes.models.Base64urlArrayBytesProperty or JSON or IO[bytes] + :param body: Is either a Base64urlArrayBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64urlArrayBytesProperty or + ~encode.bytes.types.Base64urlArrayBytesProperty or IO[bytes] :return: Base64urlArrayBytesProperty. The Base64urlArrayBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64urlArrayBytesProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/operations/_operations.py index 1975b402c705..6c5c56606a01 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..._configuration import BytesClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -142,12 +141,12 @@ def default( @overload def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.DefaultBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.DefaultBytesProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.DefaultBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -174,12 +173,13 @@ def default( @distributed_trace def default( - self, body: Union[_models2.DefaultBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models2.DefaultBytesProperty, _types_models2.DefaultBytesProperty, IO[bytes]], **kwargs: Any ) -> _models2.DefaultBytesProperty: """default. - :param body: Is one of the following types: DefaultBytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.DefaultBytesProperty or JSON or IO[bytes] + :param body: Is either a DefaultBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.DefaultBytesProperty or + ~encode.bytes.types.DefaultBytesProperty or IO[bytes] :return: DefaultBytesProperty. The DefaultBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.DefaultBytesProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -261,12 +261,12 @@ def base64( @overload def base64( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Base64BytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Base64BytesProperty: """base64. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -293,12 +293,13 @@ def base64( @distributed_trace def base64( - self, body: Union[_models2.Base64BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models2.Base64BytesProperty, _types_models2.Base64BytesProperty, IO[bytes]], **kwargs: Any ) -> _models2.Base64BytesProperty: """base64. - :param body: Is one of the following types: Base64BytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.Base64BytesProperty or JSON or IO[bytes] + :param body: Is either a Base64BytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64BytesProperty or ~encode.bytes.types.Base64BytesProperty + or IO[bytes] :return: Base64BytesProperty. The Base64BytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64BytesProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -380,12 +381,12 @@ def base64_url( @overload def base64_url( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Base64urlBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Base64urlBytesProperty: """base64_url. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64urlBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -412,12 +413,15 @@ def base64_url( @distributed_trace def base64_url( - self, body: Union[_models2.Base64urlBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.Base64urlBytesProperty, _types_models2.Base64urlBytesProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Base64urlBytesProperty: """base64_url. - :param body: Is one of the following types: Base64urlBytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.Base64urlBytesProperty or JSON or IO[bytes] + :param body: Is either a Base64urlBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64urlBytesProperty or + ~encode.bytes.types.Base64urlBytesProperty or IO[bytes] :return: Base64urlBytesProperty. The Base64urlBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64urlBytesProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -500,12 +504,12 @@ def base64_url_array( @overload def base64_url_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Base64urlArrayBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Base64urlArrayBytesProperty: """base64_url_array. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64urlArrayBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -534,13 +538,15 @@ def base64_url_array( @distributed_trace def base64_url_array( - self, body: Union[_models2.Base64urlArrayBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.Base64urlArrayBytesProperty, _types_models2.Base64urlArrayBytesProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Base64urlArrayBytesProperty: """base64_url_array. - :param body: Is one of the following types: Base64urlArrayBytesProperty, JSON, IO[bytes] - Required. - :type body: ~encode.bytes.models.Base64urlArrayBytesProperty or JSON or IO[bytes] + :param body: Is either a Base64urlArrayBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64urlArrayBytesProperty or + ~encode.bytes.types.Base64urlArrayBytesProperty or IO[bytes] :return: Base64urlArrayBytesProperty. The Base64urlArrayBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64urlArrayBytesProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/property/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/query/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/query/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/query/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/query/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/query/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/query/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/query/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/query/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/requestbody/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/requestbody/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/requestbody/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/requestbody/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/requestbody/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/requestbody/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/requestbody/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/requestbody/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/responsebody/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/responsebody/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/responsebody/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/responsebody/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/responsebody/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/responsebody/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/responsebody/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/responsebody/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/types.py index 4b7c39a67465..1d39c0328c74 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/encode/bytes/types.py @@ -13,10 +13,10 @@ class Base64BytesProperty(TypedDict, total=False): """Base64BytesProperty. :ivar value: Required. - :vartype value: bytes + :vartype value: str """ - value: Required[bytes] + value: Required[str] """Required.""" @@ -24,10 +24,10 @@ class Base64urlArrayBytesProperty(TypedDict, total=False): """Base64urlArrayBytesProperty. :ivar value: Required. - :vartype value: list[bytes] + :vartype value: list[str] """ - value: Required[list[bytes]] + value: Required[list[str]] """Required.""" @@ -35,10 +35,10 @@ class Base64urlBytesProperty(TypedDict, total=False): """Base64urlBytesProperty. :ivar value: Required. - :vartype value: bytes + :vartype value: str """ - value: Required[bytes] + value: Required[str] """Required.""" @@ -46,8 +46,8 @@ class DefaultBytesProperty(TypedDict, total=False): """DefaultBytesProperty. :ivar value: Required. - :vartype value: bytes + :vartype value: str """ - value: Required[bytes] + value: Required[str] """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/pyproject.toml index 11e758e62ab4..6f5810c6f2b3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-bytes/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/header/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/header/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/header/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/header/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/header/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/header/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/header/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/header/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/aio/operations/_operations.py index 93b3fda4678e..e1485bb59116 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/aio/operations/_operations.py @@ -26,7 +26,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from .... import models as _models3 +from .... import models as _models3, types as _types_models3 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import DatetimeClientConfiguration @@ -38,7 +38,6 @@ build_property_unix_timestamp_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -78,12 +77,12 @@ async def default( @overload async def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.DefaultDatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.DefaultDatetimeProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.DefaultDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -110,12 +109,15 @@ async def default( @distributed_trace_async async def default( - self, body: Union[_models3.DefaultDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.DefaultDatetimeProperty, _types_models3.DefaultDatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models3.DefaultDatetimeProperty: """default. - :param body: Is one of the following types: DefaultDatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.DefaultDatetimeProperty or JSON or IO[bytes] + :param body: Is either a DefaultDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.DefaultDatetimeProperty or + ~encode.datetime.types.DefaultDatetimeProperty or IO[bytes] :return: DefaultDatetimeProperty. The DefaultDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.DefaultDatetimeProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -197,12 +199,12 @@ async def rfc3339( @overload async def rfc3339( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.Rfc3339DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.Rfc3339DatetimeProperty: """rfc3339. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.Rfc3339DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -229,12 +231,15 @@ async def rfc3339( @distributed_trace_async async def rfc3339( - self, body: Union[_models3.Rfc3339DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.Rfc3339DatetimeProperty, _types_models3.Rfc3339DatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models3.Rfc3339DatetimeProperty: """rfc3339. - :param body: Is one of the following types: Rfc3339DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.Rfc3339DatetimeProperty or JSON or IO[bytes] + :param body: Is either a Rfc3339DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.Rfc3339DatetimeProperty or + ~encode.datetime.types.Rfc3339DatetimeProperty or IO[bytes] :return: Rfc3339DatetimeProperty. The Rfc3339DatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.Rfc3339DatetimeProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -316,12 +321,12 @@ async def rfc7231( @overload async def rfc7231( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.Rfc7231DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.Rfc7231DatetimeProperty: """rfc7231. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.Rfc7231DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -348,12 +353,15 @@ async def rfc7231( @distributed_trace_async async def rfc7231( - self, body: Union[_models3.Rfc7231DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.Rfc7231DatetimeProperty, _types_models3.Rfc7231DatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models3.Rfc7231DatetimeProperty: """rfc7231. - :param body: Is one of the following types: Rfc7231DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.Rfc7231DatetimeProperty or JSON or IO[bytes] + :param body: Is either a Rfc7231DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.Rfc7231DatetimeProperty or + ~encode.datetime.types.Rfc7231DatetimeProperty or IO[bytes] :return: Rfc7231DatetimeProperty. The Rfc7231DatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.Rfc7231DatetimeProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -436,12 +444,16 @@ async def unix_timestamp( @overload async def unix_timestamp( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.UnixTimestampDatetimeProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.UnixTimestampDatetimeProperty: """unix_timestamp. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.UnixTimestampDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -470,13 +482,15 @@ async def unix_timestamp( @distributed_trace_async async def unix_timestamp( - self, body: Union[_models3.UnixTimestampDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.UnixTimestampDatetimeProperty, _types_models3.UnixTimestampDatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models3.UnixTimestampDatetimeProperty: """unix_timestamp. - :param body: Is one of the following types: UnixTimestampDatetimeProperty, JSON, IO[bytes] - Required. - :type body: ~encode.datetime.models.UnixTimestampDatetimeProperty or JSON or IO[bytes] + :param body: Is either a UnixTimestampDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.UnixTimestampDatetimeProperty or + ~encode.datetime.types.UnixTimestampDatetimeProperty or IO[bytes] :return: UnixTimestampDatetimeProperty. The UnixTimestampDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.UnixTimestampDatetimeProperty @@ -564,12 +578,16 @@ async def unix_timestamp_array( @overload async def unix_timestamp_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.UnixTimestampArrayDatetimeProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.UnixTimestampArrayDatetimeProperty: """unix_timestamp_array. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.UnixTimestampArrayDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -598,13 +616,17 @@ async def unix_timestamp_array( @distributed_trace_async async def unix_timestamp_array( - self, body: Union[_models3.UnixTimestampArrayDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.UnixTimestampArrayDatetimeProperty, _types_models3.UnixTimestampArrayDatetimeProperty, IO[bytes] + ], + **kwargs: Any ) -> _models3.UnixTimestampArrayDatetimeProperty: """unix_timestamp_array. - :param body: Is one of the following types: UnixTimestampArrayDatetimeProperty, JSON, IO[bytes] - Required. - :type body: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty or JSON or IO[bytes] + :param body: Is either a UnixTimestampArrayDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty or + ~encode.datetime.types.UnixTimestampArrayDatetimeProperty or IO[bytes] :return: UnixTimestampArrayDatetimeProperty. The UnixTimestampArrayDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/operations/_operations.py index 864b7e3aaa6e..4e8b98bd09ff 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..._configuration import DatetimeClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -159,12 +158,12 @@ def default( @overload def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.DefaultDatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.DefaultDatetimeProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.DefaultDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -191,12 +190,15 @@ def default( @distributed_trace def default( - self, body: Union[_models2.DefaultDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.DefaultDatetimeProperty, _types_models2.DefaultDatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models2.DefaultDatetimeProperty: """default. - :param body: Is one of the following types: DefaultDatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.DefaultDatetimeProperty or JSON or IO[bytes] + :param body: Is either a DefaultDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.DefaultDatetimeProperty or + ~encode.datetime.types.DefaultDatetimeProperty or IO[bytes] :return: DefaultDatetimeProperty. The DefaultDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.DefaultDatetimeProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -278,12 +280,12 @@ def rfc3339( @overload def rfc3339( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Rfc3339DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Rfc3339DatetimeProperty: """rfc3339. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.Rfc3339DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -310,12 +312,15 @@ def rfc3339( @distributed_trace def rfc3339( - self, body: Union[_models2.Rfc3339DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.Rfc3339DatetimeProperty, _types_models2.Rfc3339DatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Rfc3339DatetimeProperty: """rfc3339. - :param body: Is one of the following types: Rfc3339DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.Rfc3339DatetimeProperty or JSON or IO[bytes] + :param body: Is either a Rfc3339DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.Rfc3339DatetimeProperty or + ~encode.datetime.types.Rfc3339DatetimeProperty or IO[bytes] :return: Rfc3339DatetimeProperty. The Rfc3339DatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.Rfc3339DatetimeProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -397,12 +402,12 @@ def rfc7231( @overload def rfc7231( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Rfc7231DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Rfc7231DatetimeProperty: """rfc7231. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.Rfc7231DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -429,12 +434,15 @@ def rfc7231( @distributed_trace def rfc7231( - self, body: Union[_models2.Rfc7231DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.Rfc7231DatetimeProperty, _types_models2.Rfc7231DatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Rfc7231DatetimeProperty: """rfc7231. - :param body: Is one of the following types: Rfc7231DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.Rfc7231DatetimeProperty or JSON or IO[bytes] + :param body: Is either a Rfc7231DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.Rfc7231DatetimeProperty or + ~encode.datetime.types.Rfc7231DatetimeProperty or IO[bytes] :return: Rfc7231DatetimeProperty. The Rfc7231DatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.Rfc7231DatetimeProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -517,12 +525,16 @@ def unix_timestamp( @overload def unix_timestamp( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.UnixTimestampDatetimeProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.UnixTimestampDatetimeProperty: """unix_timestamp. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.UnixTimestampDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -551,13 +563,15 @@ def unix_timestamp( @distributed_trace def unix_timestamp( - self, body: Union[_models2.UnixTimestampDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.UnixTimestampDatetimeProperty, _types_models2.UnixTimestampDatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models2.UnixTimestampDatetimeProperty: """unix_timestamp. - :param body: Is one of the following types: UnixTimestampDatetimeProperty, JSON, IO[bytes] - Required. - :type body: ~encode.datetime.models.UnixTimestampDatetimeProperty or JSON or IO[bytes] + :param body: Is either a UnixTimestampDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.UnixTimestampDatetimeProperty or + ~encode.datetime.types.UnixTimestampDatetimeProperty or IO[bytes] :return: UnixTimestampDatetimeProperty. The UnixTimestampDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.UnixTimestampDatetimeProperty @@ -645,12 +659,16 @@ def unix_timestamp_array( @overload def unix_timestamp_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.UnixTimestampArrayDatetimeProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.UnixTimestampArrayDatetimeProperty: """unix_timestamp_array. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.UnixTimestampArrayDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -679,13 +697,17 @@ def unix_timestamp_array( @distributed_trace def unix_timestamp_array( - self, body: Union[_models2.UnixTimestampArrayDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.UnixTimestampArrayDatetimeProperty, _types_models2.UnixTimestampArrayDatetimeProperty, IO[bytes] + ], + **kwargs: Any ) -> _models2.UnixTimestampArrayDatetimeProperty: """unix_timestamp_array. - :param body: Is one of the following types: UnixTimestampArrayDatetimeProperty, JSON, IO[bytes] - Required. - :type body: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty or JSON or IO[bytes] + :param body: Is either a UnixTimestampArrayDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty or + ~encode.datetime.types.UnixTimestampArrayDatetimeProperty or IO[bytes] :return: UnixTimestampArrayDatetimeProperty. The UnixTimestampArrayDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/property/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/query/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/query/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/query/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/query/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/query/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/query/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/query/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/query/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/responseheader/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/responseheader/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/responseheader/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/responseheader/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/responseheader/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/responseheader/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/responseheader/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/responseheader/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/types.py index 92a0f32c510f..b91c10e21765 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/encode/datetime/types.py @@ -6,7 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime from typing_extensions import Required, TypedDict @@ -14,10 +13,10 @@ class DefaultDatetimeProperty(TypedDict, total=False): """DefaultDatetimeProperty. :ivar value: Required. - :vartype value: ~datetime.datetime + :vartype value: str """ - value: Required[datetime.datetime] + value: Required[str] """Required.""" @@ -25,10 +24,10 @@ class Rfc3339DatetimeProperty(TypedDict, total=False): """Rfc3339DatetimeProperty. :ivar value: Required. - :vartype value: ~datetime.datetime + :vartype value: str """ - value: Required[datetime.datetime] + value: Required[str] """Required.""" @@ -36,10 +35,10 @@ class Rfc7231DatetimeProperty(TypedDict, total=False): """Rfc7231DatetimeProperty. :ivar value: Required. - :vartype value: ~datetime.datetime + :vartype value: str """ - value: Required[datetime.datetime] + value: Required[str] """Required.""" @@ -47,10 +46,10 @@ class UnixTimestampArrayDatetimeProperty(TypedDict, total=False): """UnixTimestampArrayDatetimeProperty. :ivar value: Required. - :vartype value: list[~datetime.datetime] + :vartype value: list[int] """ - value: Required[list[datetime.datetime]] + value: Required[list[int]] """Required.""" @@ -58,8 +57,8 @@ class UnixTimestampDatetimeProperty(TypedDict, total=False): """UnixTimestampDatetimeProperty. :ivar value: Required. - :vartype value: ~datetime.datetime + :vartype value: int """ - value: Required[datetime.datetime] + value: Required[int] """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/pyproject.toml index b64a64a599e2..9e293971ab3b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-datetime/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/apiview-properties.json index 090beecd114a..af313c60c11d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/apiview-properties.json +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/apiview-properties.json @@ -98,7 +98,11 @@ "encode.duration.operations.HeaderOperations.float64_milliseconds": "Encode.Duration.Header.float64Milliseconds", "encode.duration.aio.operations.HeaderOperations.float64_milliseconds": "Encode.Duration.Header.float64Milliseconds", "encode.duration.operations.HeaderOperations.int32_milliseconds_array": "Encode.Duration.Header.int32MillisecondsArray", - "encode.duration.aio.operations.HeaderOperations.int32_milliseconds_array": "Encode.Duration.Header.int32MillisecondsArray" + "encode.duration.aio.operations.HeaderOperations.int32_milliseconds_array": "Encode.Duration.Header.int32MillisecondsArray", + "encode.duration.operations.LossyOperations.int_seconds": "Encode.Duration.Lossy.intSeconds", + "encode.duration.aio.operations.LossyOperations.int_seconds": "Encode.Duration.Lossy.intSeconds", + "encode.duration.operations.LossyOperations.int_milliseconds": "Encode.Duration.Lossy.intMilliseconds", + "encode.duration.aio.operations.LossyOperations.int_milliseconds": "Encode.Duration.Lossy.intMilliseconds" }, - "CrossLanguageVersion": "59d442353391" + "CrossLanguageVersion": "1d6dc20e6d13" } \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_client.py index d42c017368fe..7e25682f3d84 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_client.py @@ -16,7 +16,7 @@ from ._configuration import DurationClientConfiguration from ._utils.serialization import Deserializer, Serializer -from .operations import HeaderOperations, PropertyOperations, QueryOperations +from .operations import HeaderOperations, LossyOperations, PropertyOperations, QueryOperations if sys.version_info >= (3, 11): from typing import Self @@ -33,6 +33,8 @@ class DurationClient: # pylint: disable=client-accepts-api-version-keyword :vartype property: encode.duration.operations.PropertyOperations :ivar header: HeaderOperations operations :vartype header: encode.duration.operations.HeaderOperations + :ivar lossy: LossyOperations operations + :vartype lossy: encode.duration.operations.LossyOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -68,6 +70,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) self.property = PropertyOperations(self._client, self._config, self._serialize, self._deserialize) self.header = HeaderOperations(self._client, self._config, self._serialize, self._deserialize) + self.lossy = LossyOperations(self._client, self._config, self._serialize, self._deserialize) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/_client.py index 6991ececbac7..2266d9125d73 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/_client.py @@ -16,7 +16,7 @@ from .._utils.serialization import Deserializer, Serializer from ._configuration import DurationClientConfiguration -from .operations import HeaderOperations, PropertyOperations, QueryOperations +from .operations import HeaderOperations, LossyOperations, PropertyOperations, QueryOperations if sys.version_info >= (3, 11): from typing import Self @@ -33,6 +33,8 @@ class DurationClient: # pylint: disable=client-accepts-api-version-keyword :vartype property: encode.duration.aio.operations.PropertyOperations :ivar header: HeaderOperations operations :vartype header: encode.duration.aio.operations.HeaderOperations + :ivar lossy: LossyOperations operations + :vartype lossy: encode.duration.aio.operations.LossyOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -68,6 +70,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) self.property = PropertyOperations(self._client, self._config, self._serialize, self._deserialize) self.header = HeaderOperations(self._client, self._config, self._serialize, self._deserialize) + self.lossy = LossyOperations(self._client, self._config, self._serialize, self._deserialize) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/__init__.py index 543a67586299..004f784f76c8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/__init__.py @@ -15,6 +15,7 @@ from ._operations import QueryOperations # type: ignore from ._operations import PropertyOperations # type: ignore from ._operations import HeaderOperations # type: ignore +from ._operations import LossyOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -24,6 +25,7 @@ "QueryOperations", "PropertyOperations", "HeaderOperations", + "LossyOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/_operations.py index 7e1848b429b3..e128ad326563 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/_operations.py @@ -28,7 +28,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -46,6 +46,8 @@ build_header_int32_seconds_request, build_header_iso8601_array_request, build_header_iso8601_request, + build_lossy_int_milliseconds_request, + build_lossy_int_seconds_request, build_property_default_request, build_property_float64_milliseconds_request, build_property_float64_seconds_request, @@ -79,7 +81,6 @@ T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] class QueryOperations: @@ -194,11 +195,11 @@ async def iso8601(self, *, input: datetime.timedelta, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_seconds(self, *, input: int, **kwargs: Any) -> None: + async def int32_seconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """int32_seconds. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -241,11 +242,11 @@ async def int32_seconds(self, *, input: int, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_seconds_larger_unit(self, *, input: int, **kwargs: Any) -> None: + async def int32_seconds_larger_unit(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """int32_seconds_larger_unit. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -288,11 +289,11 @@ async def int32_seconds_larger_unit(self, *, input: int, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float_seconds(self, *, input: float, **kwargs: Any) -> None: + async def float_seconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float_seconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -335,11 +336,11 @@ async def float_seconds(self, *, input: float, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float_seconds_larger_unit(self, *, input: float, **kwargs: Any) -> None: + async def float_seconds_larger_unit(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float_seconds_larger_unit. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -382,11 +383,11 @@ async def float_seconds_larger_unit(self, *, input: float, **kwargs: Any) -> Non return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float64_seconds(self, *, input: float, **kwargs: Any) -> None: + async def float64_seconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float64_seconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -429,11 +430,11 @@ async def float64_seconds(self, *, input: float, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_milliseconds(self, *, input: int, **kwargs: Any) -> None: + async def int32_milliseconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """int32_milliseconds. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -476,11 +477,11 @@ async def int32_milliseconds(self, *, input: int, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_milliseconds_larger_unit(self, *, input: int, **kwargs: Any) -> None: + async def int32_milliseconds_larger_unit(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """int32_milliseconds_larger_unit. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -523,11 +524,11 @@ async def int32_milliseconds_larger_unit(self, *, input: int, **kwargs: Any) -> return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float_milliseconds(self, *, input: float, **kwargs: Any) -> None: + async def float_milliseconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float_milliseconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -570,11 +571,11 @@ async def float_milliseconds(self, *, input: float, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float_milliseconds_larger_unit(self, *, input: float, **kwargs: Any) -> None: + async def float_milliseconds_larger_unit(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float_milliseconds_larger_unit. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -617,11 +618,11 @@ async def float_milliseconds_larger_unit(self, *, input: float, **kwargs: Any) - return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float64_milliseconds(self, *, input: float, **kwargs: Any) -> None: + async def float64_milliseconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float64_milliseconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -664,11 +665,11 @@ async def float64_milliseconds(self, *, input: float, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_seconds_array(self, *, input: list[int], **kwargs: Any) -> None: + async def int32_seconds_array(self, *, input: list[datetime.timedelta], **kwargs: Any) -> None: """int32_seconds_array. :keyword input: Required. - :paramtype input: list[int] + :paramtype input: list[~datetime.timedelta] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -711,11 +712,11 @@ async def int32_seconds_array(self, *, input: list[int], **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_milliseconds_array(self, *, input: list[int], **kwargs: Any) -> None: + async def int32_milliseconds_array(self, *, input: list[datetime.timedelta], **kwargs: Any) -> None: """int32_milliseconds_array. :keyword input: Required. - :paramtype input: list[int] + :paramtype input: list[~datetime.timedelta] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -793,12 +794,12 @@ async def default( @overload async def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.DefaultDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.DefaultDurationProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.DefaultDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -825,12 +826,13 @@ async def default( @distributed_trace_async async def default( - self, body: Union[_models.DefaultDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DefaultDurationProperty, _types.DefaultDurationProperty, IO[bytes]], **kwargs: Any ) -> _models.DefaultDurationProperty: """default. - :param body: Is one of the following types: DefaultDurationProperty, JSON, IO[bytes] Required. - :type body: ~encode.duration.models.DefaultDurationProperty or JSON or IO[bytes] + :param body: Is either a DefaultDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.DefaultDurationProperty or + ~encode.duration.types.DefaultDurationProperty or IO[bytes] :return: DefaultDurationProperty. The DefaultDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.DefaultDurationProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -912,12 +914,12 @@ async def iso8601( @overload async def iso8601( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ISO8601DurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ISO8601DurationProperty: """iso8601. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.ISO8601DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -944,12 +946,13 @@ async def iso8601( @distributed_trace_async async def iso8601( - self, body: Union[_models.ISO8601DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ISO8601DurationProperty, _types.ISO8601DurationProperty, IO[bytes]], **kwargs: Any ) -> _models.ISO8601DurationProperty: """iso8601. - :param body: Is one of the following types: ISO8601DurationProperty, JSON, IO[bytes] Required. - :type body: ~encode.duration.models.ISO8601DurationProperty or JSON or IO[bytes] + :param body: Is either a ISO8601DurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.ISO8601DurationProperty or + ~encode.duration.types.ISO8601DurationProperty or IO[bytes] :return: ISO8601DurationProperty. The ISO8601DurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.ISO8601DurationProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -1032,12 +1035,12 @@ async def int32_seconds( @overload async def int32_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Int32SecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Int32SecondsDurationProperty: """int32_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Int32SecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1066,13 +1069,15 @@ async def int32_seconds( @distributed_trace_async async def int32_seconds( - self, body: Union[_models.Int32SecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.Int32SecondsDurationProperty, _types.Int32SecondsDurationProperty, IO[bytes]], + **kwargs: Any ) -> _models.Int32SecondsDurationProperty: """int32_seconds. - :param body: Is one of the following types: Int32SecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.Int32SecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a Int32SecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.Int32SecondsDurationProperty or + ~encode.duration.types.Int32SecondsDurationProperty or IO[bytes] :return: Int32SecondsDurationProperty. The Int32SecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Int32SecondsDurationProperty @@ -1156,12 +1161,12 @@ async def float_seconds( @overload async def float_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.FloatSecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.FloatSecondsDurationProperty: """float_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatSecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1190,13 +1195,15 @@ async def float_seconds( @distributed_trace_async async def float_seconds( - self, body: Union[_models.FloatSecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.FloatSecondsDurationProperty, _types.FloatSecondsDurationProperty, IO[bytes]], + **kwargs: Any ) -> _models.FloatSecondsDurationProperty: """float_seconds. - :param body: Is one of the following types: FloatSecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.FloatSecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a FloatSecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.FloatSecondsDurationProperty or + ~encode.duration.types.FloatSecondsDurationProperty or IO[bytes] :return: FloatSecondsDurationProperty. The FloatSecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatSecondsDurationProperty @@ -1280,12 +1287,12 @@ async def float64_seconds( @overload async def float64_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Float64SecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Float64SecondsDurationProperty: """float64_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Float64SecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1314,13 +1321,15 @@ async def float64_seconds( @distributed_trace_async async def float64_seconds( - self, body: Union[_models.Float64SecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.Float64SecondsDurationProperty, _types.Float64SecondsDurationProperty, IO[bytes]], + **kwargs: Any ) -> _models.Float64SecondsDurationProperty: """float64_seconds. - :param body: Is one of the following types: Float64SecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.Float64SecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a Float64SecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.Float64SecondsDurationProperty or + ~encode.duration.types.Float64SecondsDurationProperty or IO[bytes] :return: Float64SecondsDurationProperty. The Float64SecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Float64SecondsDurationProperty @@ -1404,12 +1413,12 @@ async def int32_milliseconds( @overload async def int32_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Int32MillisecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Int32MillisecondsDurationProperty: """int32_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Int32MillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1438,13 +1447,15 @@ async def int32_milliseconds( @distributed_trace_async async def int32_milliseconds( - self, body: Union[_models.Int32MillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.Int32MillisecondsDurationProperty, _types.Int32MillisecondsDurationProperty, IO[bytes]], + **kwargs: Any ) -> _models.Int32MillisecondsDurationProperty: """int32_milliseconds. - :param body: Is one of the following types: Int32MillisecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.Int32MillisecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a Int32MillisecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.Int32MillisecondsDurationProperty or + ~encode.duration.types.Int32MillisecondsDurationProperty or IO[bytes] :return: Int32MillisecondsDurationProperty. The Int32MillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Int32MillisecondsDurationProperty @@ -1528,12 +1539,12 @@ async def float_milliseconds( @overload async def float_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.FloatMillisecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.FloatMillisecondsDurationProperty: """float_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatMillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1562,13 +1573,15 @@ async def float_milliseconds( @distributed_trace_async async def float_milliseconds( - self, body: Union[_models.FloatMillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.FloatMillisecondsDurationProperty, _types.FloatMillisecondsDurationProperty, IO[bytes]], + **kwargs: Any ) -> _models.FloatMillisecondsDurationProperty: """float_milliseconds. - :param body: Is one of the following types: FloatMillisecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.FloatMillisecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a FloatMillisecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.FloatMillisecondsDurationProperty or + ~encode.duration.types.FloatMillisecondsDurationProperty or IO[bytes] :return: FloatMillisecondsDurationProperty. The FloatMillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatMillisecondsDurationProperty @@ -1656,12 +1669,12 @@ async def float64_milliseconds( @overload async def float64_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Float64MillisecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Float64MillisecondsDurationProperty: """float64_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Float64MillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1690,13 +1703,16 @@ async def float64_milliseconds( @distributed_trace_async async def float64_milliseconds( - self, body: Union[_models.Float64MillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.Float64MillisecondsDurationProperty, _types.Float64MillisecondsDurationProperty, IO[bytes]], + **kwargs: Any ) -> _models.Float64MillisecondsDurationProperty: """float64_milliseconds. - :param body: Is one of the following types: Float64MillisecondsDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.Float64MillisecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a Float64MillisecondsDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.Float64MillisecondsDurationProperty or + ~encode.duration.types.Float64MillisecondsDurationProperty or IO[bytes] :return: Float64MillisecondsDurationProperty. The Float64MillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Float64MillisecondsDurationProperty @@ -1780,12 +1796,12 @@ async def float_seconds_array( @overload async def float_seconds_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.FloatSecondsDurationArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.FloatSecondsDurationArrayProperty: """float_seconds_array. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatSecondsDurationArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1814,13 +1830,15 @@ async def float_seconds_array( @distributed_trace_async async def float_seconds_array( - self, body: Union[_models.FloatSecondsDurationArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.FloatSecondsDurationArrayProperty, _types.FloatSecondsDurationArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models.FloatSecondsDurationArrayProperty: """float_seconds_array. - :param body: Is one of the following types: FloatSecondsDurationArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.FloatSecondsDurationArrayProperty or JSON or IO[bytes] + :param body: Is either a FloatSecondsDurationArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.FloatSecondsDurationArrayProperty or + ~encode.duration.types.FloatSecondsDurationArrayProperty or IO[bytes] :return: FloatSecondsDurationArrayProperty. The FloatSecondsDurationArrayProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatSecondsDurationArrayProperty @@ -1908,12 +1926,16 @@ async def float_milliseconds_array( @overload async def float_milliseconds_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types.FloatMillisecondsDurationArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.FloatMillisecondsDurationArrayProperty: """float_milliseconds_array. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatMillisecondsDurationArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1942,13 +1964,18 @@ async def float_milliseconds_array( @distributed_trace_async async def float_milliseconds_array( - self, body: Union[_models.FloatMillisecondsDurationArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.FloatMillisecondsDurationArrayProperty, _types.FloatMillisecondsDurationArrayProperty, IO[bytes] + ], + **kwargs: Any ) -> _models.FloatMillisecondsDurationArrayProperty: """float_milliseconds_array. - :param body: Is one of the following types: FloatMillisecondsDurationArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.FloatMillisecondsDurationArrayProperty or JSON or IO[bytes] + :param body: Is either a FloatMillisecondsDurationArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.FloatMillisecondsDurationArrayProperty or + ~encode.duration.types.FloatMillisecondsDurationArrayProperty or IO[bytes] :return: FloatMillisecondsDurationArrayProperty. The FloatMillisecondsDurationArrayProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatMillisecondsDurationArrayProperty @@ -2036,12 +2063,16 @@ async def int32_seconds_larger_unit( @overload async def int32_seconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types.Int32SecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.Int32SecondsLargerUnitDurationProperty: """int32_seconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Int32SecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2070,13 +2101,18 @@ async def int32_seconds_larger_unit( @distributed_trace_async async def int32_seconds_larger_unit( - self, body: Union[_models.Int32SecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.Int32SecondsLargerUnitDurationProperty, _types.Int32SecondsLargerUnitDurationProperty, IO[bytes] + ], + **kwargs: Any ) -> _models.Int32SecondsLargerUnitDurationProperty: """int32_seconds_larger_unit. - :param body: Is one of the following types: Int32SecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.Int32SecondsLargerUnitDurationProperty or JSON or IO[bytes] + :param body: Is either a Int32SecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.Int32SecondsLargerUnitDurationProperty or + ~encode.duration.types.Int32SecondsLargerUnitDurationProperty or IO[bytes] :return: Int32SecondsLargerUnitDurationProperty. The Int32SecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Int32SecondsLargerUnitDurationProperty @@ -2164,12 +2200,16 @@ async def float_seconds_larger_unit( @overload async def float_seconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types.FloatSecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.FloatSecondsLargerUnitDurationProperty: """float_seconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatSecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2198,13 +2238,18 @@ async def float_seconds_larger_unit( @distributed_trace_async async def float_seconds_larger_unit( - self, body: Union[_models.FloatSecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.FloatSecondsLargerUnitDurationProperty, _types.FloatSecondsLargerUnitDurationProperty, IO[bytes] + ], + **kwargs: Any ) -> _models.FloatSecondsLargerUnitDurationProperty: """float_seconds_larger_unit. - :param body: Is one of the following types: FloatSecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.FloatSecondsLargerUnitDurationProperty or JSON or IO[bytes] + :param body: Is either a FloatSecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.FloatSecondsLargerUnitDurationProperty or + ~encode.duration.types.FloatSecondsLargerUnitDurationProperty or IO[bytes] :return: FloatSecondsLargerUnitDurationProperty. The FloatSecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatSecondsLargerUnitDurationProperty @@ -2292,12 +2337,16 @@ async def int32_milliseconds_larger_unit( @overload async def int32_milliseconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types.Int32MillisecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.Int32MillisecondsLargerUnitDurationProperty: """int32_milliseconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Int32MillisecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2326,14 +2375,20 @@ async def int32_milliseconds_larger_unit( @distributed_trace_async async def int32_milliseconds_larger_unit( - self, body: Union[_models.Int32MillisecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.Int32MillisecondsLargerUnitDurationProperty, + _types.Int32MillisecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models.Int32MillisecondsLargerUnitDurationProperty: """int32_milliseconds_larger_unit. - :param body: Is one of the following types: Int32MillisecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.Int32MillisecondsLargerUnitDurationProperty or JSON or - IO[bytes] + :param body: Is either a Int32MillisecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.Int32MillisecondsLargerUnitDurationProperty or + ~encode.duration.types.Int32MillisecondsLargerUnitDurationProperty or IO[bytes] :return: Int32MillisecondsLargerUnitDurationProperty. The Int32MillisecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Int32MillisecondsLargerUnitDurationProperty @@ -2421,12 +2476,16 @@ async def float_milliseconds_larger_unit( @overload async def float_milliseconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types.FloatMillisecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.FloatMillisecondsLargerUnitDurationProperty: """float_milliseconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatMillisecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2455,14 +2514,20 @@ async def float_milliseconds_larger_unit( @distributed_trace_async async def float_milliseconds_larger_unit( - self, body: Union[_models.FloatMillisecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.FloatMillisecondsLargerUnitDurationProperty, + _types.FloatMillisecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models.FloatMillisecondsLargerUnitDurationProperty: """float_milliseconds_larger_unit. - :param body: Is one of the following types: FloatMillisecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.FloatMillisecondsLargerUnitDurationProperty or JSON or - IO[bytes] + :param body: Is either a FloatMillisecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.FloatMillisecondsLargerUnitDurationProperty or + ~encode.duration.types.FloatMillisecondsLargerUnitDurationProperty or IO[bytes] :return: FloatMillisecondsLargerUnitDurationProperty. The FloatMillisecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatMillisecondsLargerUnitDurationProperty @@ -2687,11 +2752,11 @@ async def iso8601_array(self, *, duration: list[datetime.timedelta], **kwargs: A return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_seconds(self, *, duration: int, **kwargs: Any) -> None: + async def int32_seconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """int32_seconds. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2734,11 +2799,11 @@ async def int32_seconds(self, *, duration: int, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_seconds_larger_unit(self, *, duration: int, **kwargs: Any) -> None: + async def int32_seconds_larger_unit(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """int32_seconds_larger_unit. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2781,11 +2846,11 @@ async def int32_seconds_larger_unit(self, *, duration: int, **kwargs: Any) -> No return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float_seconds(self, *, duration: float, **kwargs: Any) -> None: + async def float_seconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float_seconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2828,11 +2893,11 @@ async def float_seconds(self, *, duration: float, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float_seconds_larger_unit(self, *, duration: float, **kwargs: Any) -> None: + async def float_seconds_larger_unit(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float_seconds_larger_unit. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2875,11 +2940,11 @@ async def float_seconds_larger_unit(self, *, duration: float, **kwargs: Any) -> return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float64_seconds(self, *, duration: float, **kwargs: Any) -> None: + async def float64_seconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float64_seconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2922,11 +2987,11 @@ async def float64_seconds(self, *, duration: float, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_milliseconds(self, *, duration: int, **kwargs: Any) -> None: + async def int32_milliseconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """int32_milliseconds. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2969,11 +3034,11 @@ async def int32_milliseconds(self, *, duration: int, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_milliseconds_larger_unit(self, *, duration: int, **kwargs: Any) -> None: + async def int32_milliseconds_larger_unit(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """int32_milliseconds_larger_unit. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3016,11 +3081,11 @@ async def int32_milliseconds_larger_unit(self, *, duration: int, **kwargs: Any) return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float_milliseconds(self, *, duration: float, **kwargs: Any) -> None: + async def float_milliseconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float_milliseconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3063,11 +3128,11 @@ async def float_milliseconds(self, *, duration: float, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float_milliseconds_larger_unit(self, *, duration: float, **kwargs: Any) -> None: + async def float_milliseconds_larger_unit(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float_milliseconds_larger_unit. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3110,11 +3175,11 @@ async def float_milliseconds_larger_unit(self, *, duration: float, **kwargs: Any return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def float64_milliseconds(self, *, duration: float, **kwargs: Any) -> None: + async def float64_milliseconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float64_milliseconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3157,11 +3222,11 @@ async def float64_milliseconds(self, *, duration: float, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def int32_milliseconds_array(self, *, duration: list[int], **kwargs: Any) -> None: + async def int32_milliseconds_array(self, *, duration: list[datetime.timedelta], **kwargs: Any) -> None: """int32_milliseconds_array. :keyword duration: Required. - :paramtype duration: list[int] + :paramtype duration: list[~datetime.timedelta] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3202,3 +3267,115 @@ async def int32_milliseconds_array(self, *, duration: list[int], **kwargs: Any) if cls: return cls(pipeline_response, None, {}) # type: ignore + + +class LossyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~encode.duration.aio.DurationClient`'s + :attr:`lossy` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: DurationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def int_seconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: + """int_seconds. + + :keyword input: Required. + :paramtype input: ~datetime.timedelta + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_lossy_int_seconds_request( + input=input, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def int_milliseconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: + """int_milliseconds. + + :keyword input: Required. + :paramtype input: ~datetime.timedelta + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_lossy_int_milliseconds_request( + input=input, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/models/_models.py index 727d2e767f4e..c1471674750b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/models/_models.py @@ -45,17 +45,19 @@ class Float64MillisecondsDurationProperty(_Model): """Float64MillisecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -73,17 +75,19 @@ class Float64SecondsDurationProperty(_Model): """Float64SecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -101,17 +105,19 @@ class FloatMillisecondsDurationArrayProperty(_Model): """FloatMillisecondsDurationArrayProperty. :ivar value: Required. - :vartype value: list[float] + :vartype value: list[~datetime.timedelta] """ - value: list[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: list[datetime.timedelta] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-float" + ) """Required.""" @overload def __init__( self, *, - value: list[float], + value: list[datetime.timedelta], ) -> None: ... @overload @@ -129,17 +135,19 @@ class FloatMillisecondsDurationProperty(_Model): """FloatMillisecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -157,17 +165,19 @@ class FloatMillisecondsLargerUnitDurationProperty(_Model): # pylint: disable=na """FloatMillisecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -185,17 +195,19 @@ class FloatSecondsDurationArrayProperty(_Model): """FloatSecondsDurationArrayProperty. :ivar value: Required. - :vartype value: list[float] + :vartype value: list[~datetime.timedelta] """ - value: list[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: list[datetime.timedelta] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-float" + ) """Required.""" @overload def __init__( self, *, - value: list[float], + value: list[datetime.timedelta], ) -> None: ... @overload @@ -213,17 +225,19 @@ class FloatSecondsDurationProperty(_Model): """FloatSecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -241,17 +255,19 @@ class FloatSecondsLargerUnitDurationProperty(_Model): """FloatSecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -269,17 +285,19 @@ class Int32MillisecondsDurationProperty(_Model): """Int32MillisecondsDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: ~datetime.timedelta """ - value: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-int" + ) """Required.""" @overload def __init__( self, *, - value: int, + value: datetime.timedelta, ) -> None: ... @overload @@ -297,17 +315,19 @@ class Int32MillisecondsLargerUnitDurationProperty(_Model): # pylint: disable=na """Int32MillisecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: ~datetime.timedelta """ - value: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-int" + ) """Required.""" @overload def __init__( self, *, - value: int, + value: datetime.timedelta, ) -> None: ... @overload @@ -325,17 +345,19 @@ class Int32SecondsDurationProperty(_Model): """Int32SecondsDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: ~datetime.timedelta """ - value: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-int" + ) """Required.""" @overload def __init__( self, *, - value: int, + value: datetime.timedelta, ) -> None: ... @overload @@ -353,17 +375,19 @@ class Int32SecondsLargerUnitDurationProperty(_Model): """Int32SecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: ~datetime.timedelta """ - value: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-int" + ) """Required.""" @overload def __init__( self, *, - value: int, + value: datetime.timedelta, ) -> None: ... @overload diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/__init__.py index 543a67586299..004f784f76c8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/__init__.py @@ -15,6 +15,7 @@ from ._operations import QueryOperations # type: ignore from ._operations import PropertyOperations # type: ignore from ._operations import HeaderOperations # type: ignore +from ._operations import LossyOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -24,6 +25,7 @@ "QueryOperations", "PropertyOperations", "HeaderOperations", + "LossyOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/_operations.py index 4ccf6494ab6d..fe167f17e3c8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/_operations.py @@ -28,14 +28,13 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import DurationClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -65,20 +64,20 @@ def build_query_iso8601_request(*, input: datetime.timedelta, **kwargs: Any) -> return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_int32_seconds_request(*, input: int, **kwargs: Any) -> HttpRequest: +def build_query_int32_seconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/int32-seconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "int") + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-int") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_query_int32_seconds_larger_unit_request( # pylint: disable=name-too-long - *, input: int, **kwargs: Any + *, input: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -86,25 +85,25 @@ def build_query_int32_seconds_larger_unit_request( # pylint: disable=name-too-l _url = "/encode/duration/query/int32-seconds-larger-unit" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "int") + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-int") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_float_seconds_request(*, input: float, **kwargs: Any) -> HttpRequest: +def build_query_float_seconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/float-seconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_query_float_seconds_larger_unit_request( # pylint: disable=name-too-long - *, input: float, **kwargs: Any + *, input: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -112,37 +111,37 @@ def build_query_float_seconds_larger_unit_request( # pylint: disable=name-too-l _url = "/encode/duration/query/float-seconds-larger-unit" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_float64_seconds_request(*, input: float, **kwargs: Any) -> HttpRequest: +def build_query_float64_seconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/float64-seconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_int32_milliseconds_request(*, input: int, **kwargs: Any) -> HttpRequest: +def build_query_int32_milliseconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/int32-milliseconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "int") + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-int") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_query_int32_milliseconds_larger_unit_request( # pylint: disable=name-too-long - *, input: int, **kwargs: Any + *, input: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -150,25 +149,25 @@ def build_query_int32_milliseconds_larger_unit_request( # pylint: disable=name- _url = "/encode/duration/query/int32-milliseconds-larger-unit" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "int") + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-int") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_float_milliseconds_request(*, input: float, **kwargs: Any) -> HttpRequest: +def build_query_float_milliseconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/float-milliseconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_query_float_milliseconds_larger_unit_request( # pylint: disable=name-too-long - *, input: float, **kwargs: Any + *, input: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -176,37 +175,37 @@ def build_query_float_milliseconds_larger_unit_request( # pylint: disable=name- _url = "/encode/duration/query/float-milliseconds-larger-unit" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_float64_milliseconds_request(*, input: float, **kwargs: Any) -> HttpRequest: +def build_query_float64_milliseconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/float64-milliseconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_int32_seconds_array_request(*, input: list[int], **kwargs: Any) -> HttpRequest: +def build_query_int32_seconds_array_request(*, input: list[datetime.timedelta], **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/int32-seconds-array" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "[int]", div=",") + _params["input"] = _SERIALIZER.query("input", input, "[duration-seconds-int]", div=",") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_query_int32_milliseconds_array_request( # pylint: disable=name-too-long - *, input: list[int], **kwargs: Any + *, input: list[datetime.timedelta], **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -214,7 +213,7 @@ def build_query_int32_milliseconds_array_request( # pylint: disable=name-too-lo _url = "/encode/duration/query/int32-milliseconds-array" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "[int]", div=",") + _params["input"] = _SERIALIZER.query("input", input, "[duration-milliseconds-int]", div=",") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) @@ -497,20 +496,20 @@ def build_header_iso8601_array_request(*, duration: list[datetime.timedelta], ** return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_header_int32_seconds_request(*, duration: int, **kwargs: Any) -> HttpRequest: +def build_header_int32_seconds_request(*, duration: datetime.timedelta, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) # Construct URL _url = "/encode/duration/header/int32-seconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "int") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-seconds-int") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_int32_seconds_larger_unit_request( # pylint: disable=name-too-long - *, duration: int, **kwargs: Any + *, duration: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -518,25 +517,25 @@ def build_header_int32_seconds_larger_unit_request( # pylint: disable=name-too- _url = "/encode/duration/header/int32-seconds-larger-unit" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "int") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-seconds-int") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_header_float_seconds_request(*, duration: float, **kwargs: Any) -> HttpRequest: +def build_header_float_seconds_request(*, duration: datetime.timedelta, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) # Construct URL _url = "/encode/duration/header/float-seconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-seconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_float_seconds_larger_unit_request( # pylint: disable=name-too-long - *, duration: float, **kwargs: Any + *, duration: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -544,37 +543,37 @@ def build_header_float_seconds_larger_unit_request( # pylint: disable=name-too- _url = "/encode/duration/header/float-seconds-larger-unit" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-seconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_header_float64_seconds_request(*, duration: float, **kwargs: Any) -> HttpRequest: +def build_header_float64_seconds_request(*, duration: datetime.timedelta, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) # Construct URL _url = "/encode/duration/header/float64-seconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-seconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_header_int32_milliseconds_request(*, duration: int, **kwargs: Any) -> HttpRequest: +def build_header_int32_milliseconds_request(*, duration: datetime.timedelta, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) # Construct URL _url = "/encode/duration/header/int32-milliseconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "int") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-milliseconds-int") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_int32_milliseconds_larger_unit_request( # pylint: disable=name-too-long - *, duration: int, **kwargs: Any + *, duration: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -582,25 +581,25 @@ def build_header_int32_milliseconds_larger_unit_request( # pylint: disable=name _url = "/encode/duration/header/int32-milliseconds-larger-unit" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "int") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-milliseconds-int") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_header_float_milliseconds_request(*, duration: float, **kwargs: Any) -> HttpRequest: +def build_header_float_milliseconds_request(*, duration: datetime.timedelta, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) # Construct URL _url = "/encode/duration/header/float-milliseconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_float_milliseconds_larger_unit_request( # pylint: disable=name-too-long - *, duration: float, **kwargs: Any + *, duration: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -608,13 +607,13 @@ def build_header_float_milliseconds_larger_unit_request( # pylint: disable=name _url = "/encode/duration/header/float-milliseconds-larger-unit" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_float64_milliseconds_request( # pylint: disable=name-too-long - *, duration: float, **kwargs: Any + *, duration: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -622,13 +621,13 @@ def build_header_float64_milliseconds_request( # pylint: disable=name-too-long _url = "/encode/duration/header/float64-milliseconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_int32_milliseconds_array_request( # pylint: disable=name-too-long - *, duration: list[int], **kwargs: Any + *, duration: list[datetime.timedelta], **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -636,11 +635,35 @@ def build_header_int32_milliseconds_array_request( # pylint: disable=name-too-l _url = "/encode/duration/header/int32-milliseconds-array" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "[int]", div=",") + _headers["duration"] = _SERIALIZER.header("duration", duration, "[duration-milliseconds-int]", div=",") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) +def build_lossy_int_seconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/encode/duration/lossy/int32-seconds" + + # Construct parameters + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-int") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + +def build_lossy_int_milliseconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/encode/duration/lossy/int32-milliseconds" + + # Construct parameters + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-int") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + class QueryOperations: """ .. warning:: @@ -757,11 +780,13 @@ def iso8601( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def int32_seconds(self, *, input: int, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + def int32_seconds( # pylint: disable=inconsistent-return-statements + self, *, input: datetime.timedelta, **kwargs: Any + ) -> None: """int32_seconds. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -805,12 +830,12 @@ def int32_seconds(self, *, input: int, **kwargs: Any) -> None: # pylint: disabl @distributed_trace def int32_seconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, input: int, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """int32_seconds_larger_unit. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -853,11 +878,13 @@ def int32_seconds_larger_unit( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def float_seconds(self, *, input: float, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + def float_seconds( # pylint: disable=inconsistent-return-statements + self, *, input: datetime.timedelta, **kwargs: Any + ) -> None: """float_seconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -901,12 +928,12 @@ def float_seconds(self, *, input: float, **kwargs: Any) -> None: # pylint: disa @distributed_trace def float_seconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, input: float, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """float_seconds_larger_unit. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -949,11 +976,13 @@ def float_seconds_larger_unit( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def float64_seconds(self, *, input: float, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + def float64_seconds( # pylint: disable=inconsistent-return-statements + self, *, input: datetime.timedelta, **kwargs: Any + ) -> None: """float64_seconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -997,12 +1026,12 @@ def float64_seconds(self, *, input: float, **kwargs: Any) -> None: # pylint: di @distributed_trace def int32_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, input: int, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """int32_milliseconds. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1046,12 +1075,12 @@ def int32_milliseconds( # pylint: disable=inconsistent-return-statements @distributed_trace def int32_milliseconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, input: int, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """int32_milliseconds_larger_unit. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1095,12 +1124,12 @@ def int32_milliseconds_larger_unit( # pylint: disable=inconsistent-return-state @distributed_trace def float_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, input: float, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """float_milliseconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1144,12 +1173,12 @@ def float_milliseconds( # pylint: disable=inconsistent-return-statements @distributed_trace def float_milliseconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, input: float, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """float_milliseconds_larger_unit. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1193,12 +1222,12 @@ def float_milliseconds_larger_unit( # pylint: disable=inconsistent-return-state @distributed_trace def float64_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, input: float, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """float64_milliseconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1242,12 +1271,12 @@ def float64_milliseconds( # pylint: disable=inconsistent-return-statements @distributed_trace def int32_seconds_array( # pylint: disable=inconsistent-return-statements - self, *, input: list[int], **kwargs: Any + self, *, input: list[datetime.timedelta], **kwargs: Any ) -> None: """int32_seconds_array. :keyword input: Required. - :paramtype input: list[int] + :paramtype input: list[~datetime.timedelta] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1291,12 +1320,12 @@ def int32_seconds_array( # pylint: disable=inconsistent-return-statements @distributed_trace def int32_milliseconds_array( # pylint: disable=inconsistent-return-statements - self, *, input: list[int], **kwargs: Any + self, *, input: list[datetime.timedelta], **kwargs: Any ) -> None: """int32_milliseconds_array. :keyword input: Required. - :paramtype input: list[int] + :paramtype input: list[~datetime.timedelta] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1374,12 +1403,12 @@ def default( @overload def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.DefaultDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.DefaultDurationProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.DefaultDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1406,12 +1435,13 @@ def default( @distributed_trace def default( - self, body: Union[_models.DefaultDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DefaultDurationProperty, _types.DefaultDurationProperty, IO[bytes]], **kwargs: Any ) -> _models.DefaultDurationProperty: """default. - :param body: Is one of the following types: DefaultDurationProperty, JSON, IO[bytes] Required. - :type body: ~encode.duration.models.DefaultDurationProperty or JSON or IO[bytes] + :param body: Is either a DefaultDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.DefaultDurationProperty or + ~encode.duration.types.DefaultDurationProperty or IO[bytes] :return: DefaultDurationProperty. The DefaultDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.DefaultDurationProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -1493,12 +1523,12 @@ def iso8601( @overload def iso8601( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ISO8601DurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ISO8601DurationProperty: """iso8601. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.ISO8601DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1525,12 +1555,13 @@ def iso8601( @distributed_trace def iso8601( - self, body: Union[_models.ISO8601DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ISO8601DurationProperty, _types.ISO8601DurationProperty, IO[bytes]], **kwargs: Any ) -> _models.ISO8601DurationProperty: """iso8601. - :param body: Is one of the following types: ISO8601DurationProperty, JSON, IO[bytes] Required. - :type body: ~encode.duration.models.ISO8601DurationProperty or JSON or IO[bytes] + :param body: Is either a ISO8601DurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.ISO8601DurationProperty or + ~encode.duration.types.ISO8601DurationProperty or IO[bytes] :return: ISO8601DurationProperty. The ISO8601DurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.ISO8601DurationProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -1613,12 +1644,12 @@ def int32_seconds( @overload def int32_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Int32SecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Int32SecondsDurationProperty: """int32_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Int32SecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1647,13 +1678,15 @@ def int32_seconds( @distributed_trace def int32_seconds( - self, body: Union[_models.Int32SecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.Int32SecondsDurationProperty, _types.Int32SecondsDurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models.Int32SecondsDurationProperty: """int32_seconds. - :param body: Is one of the following types: Int32SecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.Int32SecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a Int32SecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.Int32SecondsDurationProperty or + ~encode.duration.types.Int32SecondsDurationProperty or IO[bytes] :return: Int32SecondsDurationProperty. The Int32SecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Int32SecondsDurationProperty @@ -1737,12 +1770,12 @@ def float_seconds( @overload def float_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.FloatSecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.FloatSecondsDurationProperty: """float_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatSecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1771,13 +1804,15 @@ def float_seconds( @distributed_trace def float_seconds( - self, body: Union[_models.FloatSecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.FloatSecondsDurationProperty, _types.FloatSecondsDurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models.FloatSecondsDurationProperty: """float_seconds. - :param body: Is one of the following types: FloatSecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.FloatSecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a FloatSecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.FloatSecondsDurationProperty or + ~encode.duration.types.FloatSecondsDurationProperty or IO[bytes] :return: FloatSecondsDurationProperty. The FloatSecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatSecondsDurationProperty @@ -1861,12 +1896,12 @@ def float64_seconds( @overload def float64_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Float64SecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Float64SecondsDurationProperty: """float64_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Float64SecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1895,13 +1930,15 @@ def float64_seconds( @distributed_trace def float64_seconds( - self, body: Union[_models.Float64SecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.Float64SecondsDurationProperty, _types.Float64SecondsDurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models.Float64SecondsDurationProperty: """float64_seconds. - :param body: Is one of the following types: Float64SecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.Float64SecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a Float64SecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.Float64SecondsDurationProperty or + ~encode.duration.types.Float64SecondsDurationProperty or IO[bytes] :return: Float64SecondsDurationProperty. The Float64SecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Float64SecondsDurationProperty @@ -1985,12 +2022,12 @@ def int32_milliseconds( @overload def int32_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Int32MillisecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Int32MillisecondsDurationProperty: """int32_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Int32MillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2019,13 +2056,15 @@ def int32_milliseconds( @distributed_trace def int32_milliseconds( - self, body: Union[_models.Int32MillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.Int32MillisecondsDurationProperty, _types.Int32MillisecondsDurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models.Int32MillisecondsDurationProperty: """int32_milliseconds. - :param body: Is one of the following types: Int32MillisecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.Int32MillisecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a Int32MillisecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.Int32MillisecondsDurationProperty or + ~encode.duration.types.Int32MillisecondsDurationProperty or IO[bytes] :return: Int32MillisecondsDurationProperty. The Int32MillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Int32MillisecondsDurationProperty @@ -2109,12 +2148,12 @@ def float_milliseconds( @overload def float_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.FloatMillisecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.FloatMillisecondsDurationProperty: """float_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatMillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2143,13 +2182,15 @@ def float_milliseconds( @distributed_trace def float_milliseconds( - self, body: Union[_models.FloatMillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.FloatMillisecondsDurationProperty, _types.FloatMillisecondsDurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models.FloatMillisecondsDurationProperty: """float_milliseconds. - :param body: Is one of the following types: FloatMillisecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.FloatMillisecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a FloatMillisecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.FloatMillisecondsDurationProperty or + ~encode.duration.types.FloatMillisecondsDurationProperty or IO[bytes] :return: FloatMillisecondsDurationProperty. The FloatMillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatMillisecondsDurationProperty @@ -2237,12 +2278,12 @@ def float64_milliseconds( @overload def float64_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Float64MillisecondsDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Float64MillisecondsDurationProperty: """float64_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Float64MillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2271,13 +2312,16 @@ def float64_milliseconds( @distributed_trace def float64_milliseconds( - self, body: Union[_models.Float64MillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.Float64MillisecondsDurationProperty, _types.Float64MillisecondsDurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models.Float64MillisecondsDurationProperty: """float64_milliseconds. - :param body: Is one of the following types: Float64MillisecondsDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.Float64MillisecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a Float64MillisecondsDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.Float64MillisecondsDurationProperty or + ~encode.duration.types.Float64MillisecondsDurationProperty or IO[bytes] :return: Float64MillisecondsDurationProperty. The Float64MillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Float64MillisecondsDurationProperty @@ -2361,12 +2405,12 @@ def float_seconds_array( @overload def float_seconds_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.FloatSecondsDurationArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.FloatSecondsDurationArrayProperty: """float_seconds_array. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatSecondsDurationArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2395,13 +2439,15 @@ def float_seconds_array( @distributed_trace def float_seconds_array( - self, body: Union[_models.FloatSecondsDurationArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.FloatSecondsDurationArrayProperty, _types.FloatSecondsDurationArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models.FloatSecondsDurationArrayProperty: """float_seconds_array. - :param body: Is one of the following types: FloatSecondsDurationArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.models.FloatSecondsDurationArrayProperty or JSON or IO[bytes] + :param body: Is either a FloatSecondsDurationArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.models.FloatSecondsDurationArrayProperty or + ~encode.duration.types.FloatSecondsDurationArrayProperty or IO[bytes] :return: FloatSecondsDurationArrayProperty. The FloatSecondsDurationArrayProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatSecondsDurationArrayProperty @@ -2489,12 +2535,16 @@ def float_milliseconds_array( @overload def float_milliseconds_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types.FloatMillisecondsDurationArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models.FloatMillisecondsDurationArrayProperty: """float_milliseconds_array. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatMillisecondsDurationArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2523,13 +2573,18 @@ def float_milliseconds_array( @distributed_trace def float_milliseconds_array( - self, body: Union[_models.FloatMillisecondsDurationArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.FloatMillisecondsDurationArrayProperty, _types.FloatMillisecondsDurationArrayProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models.FloatMillisecondsDurationArrayProperty: """float_milliseconds_array. - :param body: Is one of the following types: FloatMillisecondsDurationArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.FloatMillisecondsDurationArrayProperty or JSON or IO[bytes] + :param body: Is either a FloatMillisecondsDurationArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.FloatMillisecondsDurationArrayProperty or + ~encode.duration.types.FloatMillisecondsDurationArrayProperty or IO[bytes] :return: FloatMillisecondsDurationArrayProperty. The FloatMillisecondsDurationArrayProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatMillisecondsDurationArrayProperty @@ -2617,12 +2672,16 @@ def int32_seconds_larger_unit( @overload def int32_seconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types.Int32SecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models.Int32SecondsLargerUnitDurationProperty: """int32_seconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Int32SecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2651,13 +2710,18 @@ def int32_seconds_larger_unit( @distributed_trace def int32_seconds_larger_unit( - self, body: Union[_models.Int32SecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.Int32SecondsLargerUnitDurationProperty, _types.Int32SecondsLargerUnitDurationProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models.Int32SecondsLargerUnitDurationProperty: """int32_seconds_larger_unit. - :param body: Is one of the following types: Int32SecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.Int32SecondsLargerUnitDurationProperty or JSON or IO[bytes] + :param body: Is either a Int32SecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.Int32SecondsLargerUnitDurationProperty or + ~encode.duration.types.Int32SecondsLargerUnitDurationProperty or IO[bytes] :return: Int32SecondsLargerUnitDurationProperty. The Int32SecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Int32SecondsLargerUnitDurationProperty @@ -2745,12 +2809,16 @@ def float_seconds_larger_unit( @overload def float_seconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types.FloatSecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models.FloatSecondsLargerUnitDurationProperty: """float_seconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatSecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2779,13 +2847,18 @@ def float_seconds_larger_unit( @distributed_trace def float_seconds_larger_unit( - self, body: Union[_models.FloatSecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.FloatSecondsLargerUnitDurationProperty, _types.FloatSecondsLargerUnitDurationProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models.FloatSecondsLargerUnitDurationProperty: """float_seconds_larger_unit. - :param body: Is one of the following types: FloatSecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.FloatSecondsLargerUnitDurationProperty or JSON or IO[bytes] + :param body: Is either a FloatSecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.FloatSecondsLargerUnitDurationProperty or + ~encode.duration.types.FloatSecondsLargerUnitDurationProperty or IO[bytes] :return: FloatSecondsLargerUnitDurationProperty. The FloatSecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatSecondsLargerUnitDurationProperty @@ -2873,12 +2946,16 @@ def int32_milliseconds_larger_unit( @overload def int32_milliseconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types.Int32MillisecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models.Int32MillisecondsLargerUnitDurationProperty: """int32_milliseconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.Int32MillisecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2907,14 +2984,20 @@ def int32_milliseconds_larger_unit( @distributed_trace def int32_milliseconds_larger_unit( - self, body: Union[_models.Int32MillisecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.Int32MillisecondsLargerUnitDurationProperty, + _types.Int32MillisecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models.Int32MillisecondsLargerUnitDurationProperty: """int32_milliseconds_larger_unit. - :param body: Is one of the following types: Int32MillisecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.Int32MillisecondsLargerUnitDurationProperty or JSON or - IO[bytes] + :param body: Is either a Int32MillisecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.Int32MillisecondsLargerUnitDurationProperty or + ~encode.duration.types.Int32MillisecondsLargerUnitDurationProperty or IO[bytes] :return: Int32MillisecondsLargerUnitDurationProperty. The Int32MillisecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.Int32MillisecondsLargerUnitDurationProperty @@ -3002,12 +3085,16 @@ def float_milliseconds_larger_unit( @overload def float_milliseconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types.FloatMillisecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models.FloatMillisecondsLargerUnitDurationProperty: """float_milliseconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.types.FloatMillisecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3036,14 +3123,20 @@ def float_milliseconds_larger_unit( @distributed_trace def float_milliseconds_larger_unit( - self, body: Union[_models.FloatMillisecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.FloatMillisecondsLargerUnitDurationProperty, + _types.FloatMillisecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models.FloatMillisecondsLargerUnitDurationProperty: """float_milliseconds_larger_unit. - :param body: Is one of the following types: FloatMillisecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.models.FloatMillisecondsLargerUnitDurationProperty or JSON or - IO[bytes] + :param body: Is either a FloatMillisecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.models.FloatMillisecondsLargerUnitDurationProperty or + ~encode.duration.types.FloatMillisecondsLargerUnitDurationProperty or IO[bytes] :return: FloatMillisecondsLargerUnitDurationProperty. The FloatMillisecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.models.FloatMillisecondsLargerUnitDurationProperty @@ -3274,11 +3367,13 @@ def iso8601_array( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def int32_seconds(self, *, duration: int, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + def int32_seconds( # pylint: disable=inconsistent-return-statements + self, *, duration: datetime.timedelta, **kwargs: Any + ) -> None: """int32_seconds. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3322,12 +3417,12 @@ def int32_seconds(self, *, duration: int, **kwargs: Any) -> None: # pylint: dis @distributed_trace def int32_seconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, duration: int, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """int32_seconds_larger_unit. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3371,12 +3466,12 @@ def int32_seconds_larger_unit( # pylint: disable=inconsistent-return-statements @distributed_trace def float_seconds( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float_seconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3420,12 +3515,12 @@ def float_seconds( # pylint: disable=inconsistent-return-statements @distributed_trace def float_seconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float_seconds_larger_unit. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3469,12 +3564,12 @@ def float_seconds_larger_unit( # pylint: disable=inconsistent-return-statements @distributed_trace def float64_seconds( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float64_seconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3518,12 +3613,12 @@ def float64_seconds( # pylint: disable=inconsistent-return-statements @distributed_trace def int32_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, duration: int, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """int32_milliseconds. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3567,12 +3662,12 @@ def int32_milliseconds( # pylint: disable=inconsistent-return-statements @distributed_trace def int32_milliseconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, duration: int, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """int32_milliseconds_larger_unit. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3616,12 +3711,12 @@ def int32_milliseconds_larger_unit( # pylint: disable=inconsistent-return-state @distributed_trace def float_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float_milliseconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3665,12 +3760,12 @@ def float_milliseconds( # pylint: disable=inconsistent-return-statements @distributed_trace def float_milliseconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float_milliseconds_larger_unit. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3714,12 +3809,12 @@ def float_milliseconds_larger_unit( # pylint: disable=inconsistent-return-state @distributed_trace def float64_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float64_milliseconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3763,12 +3858,12 @@ def float64_milliseconds( # pylint: disable=inconsistent-return-statements @distributed_trace def int32_milliseconds_array( # pylint: disable=inconsistent-return-statements - self, *, duration: list[int], **kwargs: Any + self, *, duration: list[datetime.timedelta], **kwargs: Any ) -> None: """int32_milliseconds_array. :keyword duration: Required. - :paramtype duration: list[int] + :paramtype duration: list[~datetime.timedelta] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3809,3 +3904,119 @@ def int32_milliseconds_array( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) # type: ignore + + +class LossyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~encode.duration.DurationClient`'s + :attr:`lossy` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: DurationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def int_seconds( # pylint: disable=inconsistent-return-statements + self, *, input: datetime.timedelta, **kwargs: Any + ) -> None: + """int_seconds. + + :keyword input: Required. + :paramtype input: ~datetime.timedelta + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_lossy_int_seconds_request( + input=input, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def int_milliseconds( # pylint: disable=inconsistent-return-statements + self, *, input: datetime.timedelta, **kwargs: Any + ) -> None: + """int_milliseconds. + + :keyword input: Required. + :paramtype input: ~datetime.timedelta + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_lossy_int_milliseconds_request( + input=input, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/types.py index fb93fc55918e..203342f02859 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/encode/duration/types.py @@ -6,7 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime from typing_extensions import Required, TypedDict @@ -14,10 +13,10 @@ class DefaultDurationProperty(TypedDict, total=False): """DefaultDurationProperty. :ivar value: Required. - :vartype value: ~datetime.timedelta + :vartype value: str """ - value: Required[datetime.timedelta] + value: Required[str] """Required.""" @@ -25,10 +24,10 @@ class Float64MillisecondsDurationProperty(TypedDict, total=False): """Float64MillisecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -36,10 +35,10 @@ class Float64SecondsDurationProperty(TypedDict, total=False): """Float64SecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -47,10 +46,10 @@ class FloatMillisecondsDurationArrayProperty(TypedDict, total=False): """FloatMillisecondsDurationArrayProperty. :ivar value: Required. - :vartype value: list[float] + :vartype value: list[str] """ - value: Required[list[float]] + value: Required[list[str]] """Required.""" @@ -58,10 +57,10 @@ class FloatMillisecondsDurationProperty(TypedDict, total=False): """FloatMillisecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -69,10 +68,10 @@ class FloatMillisecondsLargerUnitDurationProperty(TypedDict, total=False): # py """FloatMillisecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -80,10 +79,10 @@ class FloatSecondsDurationArrayProperty(TypedDict, total=False): """FloatSecondsDurationArrayProperty. :ivar value: Required. - :vartype value: list[float] + :vartype value: list[str] """ - value: Required[list[float]] + value: Required[list[str]] """Required.""" @@ -91,10 +90,10 @@ class FloatSecondsDurationProperty(TypedDict, total=False): """FloatSecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -102,10 +101,10 @@ class FloatSecondsLargerUnitDurationProperty(TypedDict, total=False): """FloatSecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -113,10 +112,10 @@ class Int32MillisecondsDurationProperty(TypedDict, total=False): """Int32MillisecondsDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: str """ - value: Required[int] + value: Required[str] """Required.""" @@ -124,10 +123,10 @@ class Int32MillisecondsLargerUnitDurationProperty(TypedDict, total=False): # py """Int32MillisecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: str """ - value: Required[int] + value: Required[str] """Required.""" @@ -135,10 +134,10 @@ class Int32SecondsDurationProperty(TypedDict, total=False): """Int32SecondsDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: str """ - value: Required[int] + value: Required[str] """Required.""" @@ -146,10 +145,10 @@ class Int32SecondsLargerUnitDurationProperty(TypedDict, total=False): """Int32SecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: str """ - value: Required[int] + value: Required[str] """Required.""" @@ -157,8 +156,8 @@ class ISO8601DurationProperty(TypedDict, total=False): """ISO8601DurationProperty. :ivar value: Required. - :vartype value: ~datetime.timedelta + :vartype value: str """ - value: Required[datetime.timedelta] + value: Required[str] """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_header_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_header_operations.py index 17f12951c10d..a078d4555915 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_header_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_header_operations.py @@ -50,7 +50,7 @@ def test_header_iso8601_array(self, duration_endpoint): def test_header_int32_seconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.int32_seconds( - duration=0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -61,7 +61,7 @@ def test_header_int32_seconds(self, duration_endpoint): def test_header_int32_seconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.int32_seconds_larger_unit( - duration=0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -72,7 +72,7 @@ def test_header_int32_seconds_larger_unit(self, duration_endpoint): def test_header_float_seconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.float_seconds( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -83,7 +83,7 @@ def test_header_float_seconds(self, duration_endpoint): def test_header_float_seconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.float_seconds_larger_unit( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -94,7 +94,7 @@ def test_header_float_seconds_larger_unit(self, duration_endpoint): def test_header_float64_seconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.float64_seconds( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -105,7 +105,7 @@ def test_header_float64_seconds(self, duration_endpoint): def test_header_int32_milliseconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.int32_milliseconds( - duration=0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -116,7 +116,7 @@ def test_header_int32_milliseconds(self, duration_endpoint): def test_header_int32_milliseconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.int32_milliseconds_larger_unit( - duration=0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -127,7 +127,7 @@ def test_header_int32_milliseconds_larger_unit(self, duration_endpoint): def test_header_float_milliseconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.float_milliseconds( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -138,7 +138,7 @@ def test_header_float_milliseconds(self, duration_endpoint): def test_header_float_milliseconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.float_milliseconds_larger_unit( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -149,7 +149,7 @@ def test_header_float_milliseconds_larger_unit(self, duration_endpoint): def test_header_float64_milliseconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.float64_milliseconds( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -160,7 +160,7 @@ def test_header_float64_milliseconds(self, duration_endpoint): def test_header_int32_milliseconds_array(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.header.int32_milliseconds_array( - duration=[0], + duration=["1 day, 0:00:00"], ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_header_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_header_operations_async.py index 3bbff2db60ee..2e2d49c14cb6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_header_operations_async.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_header_operations_async.py @@ -51,7 +51,7 @@ async def test_header_iso8601_array(self, duration_endpoint): async def test_header_int32_seconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.int32_seconds( - duration=0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -62,7 +62,7 @@ async def test_header_int32_seconds(self, duration_endpoint): async def test_header_int32_seconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.int32_seconds_larger_unit( - duration=0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -73,7 +73,7 @@ async def test_header_int32_seconds_larger_unit(self, duration_endpoint): async def test_header_float_seconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.float_seconds( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -84,7 +84,7 @@ async def test_header_float_seconds(self, duration_endpoint): async def test_header_float_seconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.float_seconds_larger_unit( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -95,7 +95,7 @@ async def test_header_float_seconds_larger_unit(self, duration_endpoint): async def test_header_float64_seconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.float64_seconds( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -106,7 +106,7 @@ async def test_header_float64_seconds(self, duration_endpoint): async def test_header_int32_milliseconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.int32_milliseconds( - duration=0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -117,7 +117,7 @@ async def test_header_int32_milliseconds(self, duration_endpoint): async def test_header_int32_milliseconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.int32_milliseconds_larger_unit( - duration=0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -128,7 +128,7 @@ async def test_header_int32_milliseconds_larger_unit(self, duration_endpoint): async def test_header_float_milliseconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.float_milliseconds( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -139,7 +139,7 @@ async def test_header_float_milliseconds(self, duration_endpoint): async def test_header_float_milliseconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.float_milliseconds_larger_unit( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -150,7 +150,7 @@ async def test_header_float_milliseconds_larger_unit(self, duration_endpoint): async def test_header_float64_milliseconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.float64_milliseconds( - duration=0.0, + duration="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -161,7 +161,7 @@ async def test_header_float64_milliseconds(self, duration_endpoint): async def test_header_int32_milliseconds_array(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.header.int32_milliseconds_array( - duration=[0], + duration=["1 day, 0:00:00"], ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_header_param.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_lossy_operations.py similarity index 58% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_header_param.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_lossy_operations.py index b31ec5cf5001..06b0e6e86069 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_header_param.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_lossy_operations.py @@ -7,28 +7,28 @@ # -------------------------------------------------------------------------- import pytest from devtools_testutils import recorded_by_proxy -from testpreparer import HeaderParamClientTestBase, HeaderParamPreparer +from testpreparer import DurationClientTestBase, DurationPreparer @pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestHeaderParam(HeaderParamClientTestBase): - @HeaderParamPreparer() +class TestDurationLossyOperations(DurationClientTestBase): + @DurationPreparer() @recorded_by_proxy - def test_with_query(self, headerparam_endpoint): - client = self.create_client(endpoint=headerparam_endpoint) - response = client.with_query( - id="str", + def test_lossy_int_seconds(self, duration_endpoint): + client = self.create_client(endpoint=duration_endpoint) + response = client.lossy.int_seconds( + input="1 day, 0:00:00", ) # please add some check logic here by yourself # ... - @HeaderParamPreparer() + @DurationPreparer() @recorded_by_proxy - def test_with_body(self, headerparam_endpoint): - client = self.create_client(endpoint=headerparam_endpoint) - response = client.with_body( - body={"name": "str"}, + def test_lossy_int_milliseconds(self, duration_endpoint): + client = self.create_client(endpoint=duration_endpoint) + response = client.lossy.int_milliseconds( + input="1 day, 0:00:00", ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_header_param_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_lossy_operations_async.py similarity index 55% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_header_param_async.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_lossy_operations_async.py index 787cb30d7bf4..b692f402212f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/generated_tests/test_header_param_async.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_lossy_operations_async.py @@ -7,29 +7,29 @@ # -------------------------------------------------------------------------- import pytest from devtools_testutils.aio import recorded_by_proxy_async -from testpreparer import HeaderParamPreparer -from testpreparer_async import HeaderParamClientTestBaseAsync +from testpreparer import DurationPreparer +from testpreparer_async import DurationClientTestBaseAsync @pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestHeaderParamAsync(HeaderParamClientTestBaseAsync): - @HeaderParamPreparer() +class TestDurationLossyOperationsAsync(DurationClientTestBaseAsync): + @DurationPreparer() @recorded_by_proxy_async - async def test_with_query(self, headerparam_endpoint): - client = self.create_async_client(endpoint=headerparam_endpoint) - response = await client.with_query( - id="str", + async def test_lossy_int_seconds(self, duration_endpoint): + client = self.create_async_client(endpoint=duration_endpoint) + response = await client.lossy.int_seconds( + input="1 day, 0:00:00", ) # please add some check logic here by yourself # ... - @HeaderParamPreparer() + @DurationPreparer() @recorded_by_proxy_async - async def test_with_body(self, headerparam_endpoint): - client = self.create_async_client(endpoint=headerparam_endpoint) - response = await client.with_body( - body={"name": "str"}, + async def test_lossy_int_milliseconds(self, duration_endpoint): + client = self.create_async_client(endpoint=duration_endpoint) + response = await client.lossy.int_milliseconds( + input="1 day, 0:00:00", ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_property_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_property_operations.py index 631c71df32fc..82065db008cd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_property_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_property_operations.py @@ -39,7 +39,7 @@ def test_property_iso8601(self, duration_endpoint): def test_property_int32_seconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.int32_seconds( - body={"value": 0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -50,7 +50,7 @@ def test_property_int32_seconds(self, duration_endpoint): def test_property_float_seconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.float_seconds( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -61,7 +61,7 @@ def test_property_float_seconds(self, duration_endpoint): def test_property_float64_seconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.float64_seconds( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -72,7 +72,7 @@ def test_property_float64_seconds(self, duration_endpoint): def test_property_int32_milliseconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.int32_milliseconds( - body={"value": 0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -83,7 +83,7 @@ def test_property_int32_milliseconds(self, duration_endpoint): def test_property_float_milliseconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.float_milliseconds( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -94,7 +94,7 @@ def test_property_float_milliseconds(self, duration_endpoint): def test_property_float64_milliseconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.float64_milliseconds( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -105,7 +105,7 @@ def test_property_float64_milliseconds(self, duration_endpoint): def test_property_float_seconds_array(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.float_seconds_array( - body={"value": [0.0]}, + body={"value": ["1 day, 0:00:00"]}, ) # please add some check logic here by yourself @@ -116,7 +116,7 @@ def test_property_float_seconds_array(self, duration_endpoint): def test_property_float_milliseconds_array(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.float_milliseconds_array( - body={"value": [0.0]}, + body={"value": ["1 day, 0:00:00"]}, ) # please add some check logic here by yourself @@ -127,7 +127,7 @@ def test_property_float_milliseconds_array(self, duration_endpoint): def test_property_int32_seconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.int32_seconds_larger_unit( - body={"value": 0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -138,7 +138,7 @@ def test_property_int32_seconds_larger_unit(self, duration_endpoint): def test_property_float_seconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.float_seconds_larger_unit( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -149,7 +149,7 @@ def test_property_float_seconds_larger_unit(self, duration_endpoint): def test_property_int32_milliseconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.int32_milliseconds_larger_unit( - body={"value": 0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -160,7 +160,7 @@ def test_property_int32_milliseconds_larger_unit(self, duration_endpoint): def test_property_float_milliseconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.property.float_milliseconds_larger_unit( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_property_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_property_operations_async.py index dc6aa273dfe5..bed30f8cf130 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_property_operations_async.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_property_operations_async.py @@ -40,7 +40,7 @@ async def test_property_iso8601(self, duration_endpoint): async def test_property_int32_seconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.int32_seconds( - body={"value": 0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -51,7 +51,7 @@ async def test_property_int32_seconds(self, duration_endpoint): async def test_property_float_seconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.float_seconds( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -62,7 +62,7 @@ async def test_property_float_seconds(self, duration_endpoint): async def test_property_float64_seconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.float64_seconds( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -73,7 +73,7 @@ async def test_property_float64_seconds(self, duration_endpoint): async def test_property_int32_milliseconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.int32_milliseconds( - body={"value": 0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -84,7 +84,7 @@ async def test_property_int32_milliseconds(self, duration_endpoint): async def test_property_float_milliseconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.float_milliseconds( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -95,7 +95,7 @@ async def test_property_float_milliseconds(self, duration_endpoint): async def test_property_float64_milliseconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.float64_milliseconds( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -106,7 +106,7 @@ async def test_property_float64_milliseconds(self, duration_endpoint): async def test_property_float_seconds_array(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.float_seconds_array( - body={"value": [0.0]}, + body={"value": ["1 day, 0:00:00"]}, ) # please add some check logic here by yourself @@ -117,7 +117,7 @@ async def test_property_float_seconds_array(self, duration_endpoint): async def test_property_float_milliseconds_array(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.float_milliseconds_array( - body={"value": [0.0]}, + body={"value": ["1 day, 0:00:00"]}, ) # please add some check logic here by yourself @@ -128,7 +128,7 @@ async def test_property_float_milliseconds_array(self, duration_endpoint): async def test_property_int32_seconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.int32_seconds_larger_unit( - body={"value": 0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -139,7 +139,7 @@ async def test_property_int32_seconds_larger_unit(self, duration_endpoint): async def test_property_float_seconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.float_seconds_larger_unit( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -150,7 +150,7 @@ async def test_property_float_seconds_larger_unit(self, duration_endpoint): async def test_property_int32_milliseconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.int32_milliseconds_larger_unit( - body={"value": 0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself @@ -161,7 +161,7 @@ async def test_property_int32_milliseconds_larger_unit(self, duration_endpoint): async def test_property_float_milliseconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.property.float_milliseconds_larger_unit( - body={"value": 0.0}, + body={"value": "1 day, 0:00:00"}, ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_query_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_query_operations.py index 985b6a3e6a47..970a3752eb88 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_query_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_query_operations.py @@ -39,7 +39,7 @@ def test_query_iso8601(self, duration_endpoint): def test_query_int32_seconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.int32_seconds( - input=0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -50,7 +50,7 @@ def test_query_int32_seconds(self, duration_endpoint): def test_query_int32_seconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.int32_seconds_larger_unit( - input=0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -61,7 +61,7 @@ def test_query_int32_seconds_larger_unit(self, duration_endpoint): def test_query_float_seconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.float_seconds( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -72,7 +72,7 @@ def test_query_float_seconds(self, duration_endpoint): def test_query_float_seconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.float_seconds_larger_unit( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -83,7 +83,7 @@ def test_query_float_seconds_larger_unit(self, duration_endpoint): def test_query_float64_seconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.float64_seconds( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -94,7 +94,7 @@ def test_query_float64_seconds(self, duration_endpoint): def test_query_int32_milliseconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.int32_milliseconds( - input=0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -105,7 +105,7 @@ def test_query_int32_milliseconds(self, duration_endpoint): def test_query_int32_milliseconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.int32_milliseconds_larger_unit( - input=0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -116,7 +116,7 @@ def test_query_int32_milliseconds_larger_unit(self, duration_endpoint): def test_query_float_milliseconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.float_milliseconds( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -127,7 +127,7 @@ def test_query_float_milliseconds(self, duration_endpoint): def test_query_float_milliseconds_larger_unit(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.float_milliseconds_larger_unit( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -138,7 +138,7 @@ def test_query_float_milliseconds_larger_unit(self, duration_endpoint): def test_query_float64_milliseconds(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.float64_milliseconds( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -149,7 +149,7 @@ def test_query_float64_milliseconds(self, duration_endpoint): def test_query_int32_seconds_array(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.int32_seconds_array( - input=[0], + input=["1 day, 0:00:00"], ) # please add some check logic here by yourself @@ -160,7 +160,7 @@ def test_query_int32_seconds_array(self, duration_endpoint): def test_query_int32_milliseconds_array(self, duration_endpoint): client = self.create_client(endpoint=duration_endpoint) response = client.query.int32_milliseconds_array( - input=[0], + input=["1 day, 0:00:00"], ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_query_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_query_operations_async.py index 26fcb3c6dd89..b8352919dba6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_query_operations_async.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/generated_tests/test_duration_query_operations_async.py @@ -40,7 +40,7 @@ async def test_query_iso8601(self, duration_endpoint): async def test_query_int32_seconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.int32_seconds( - input=0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -51,7 +51,7 @@ async def test_query_int32_seconds(self, duration_endpoint): async def test_query_int32_seconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.int32_seconds_larger_unit( - input=0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -62,7 +62,7 @@ async def test_query_int32_seconds_larger_unit(self, duration_endpoint): async def test_query_float_seconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.float_seconds( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -73,7 +73,7 @@ async def test_query_float_seconds(self, duration_endpoint): async def test_query_float_seconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.float_seconds_larger_unit( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -84,7 +84,7 @@ async def test_query_float_seconds_larger_unit(self, duration_endpoint): async def test_query_float64_seconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.float64_seconds( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -95,7 +95,7 @@ async def test_query_float64_seconds(self, duration_endpoint): async def test_query_int32_milliseconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.int32_milliseconds( - input=0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -106,7 +106,7 @@ async def test_query_int32_milliseconds(self, duration_endpoint): async def test_query_int32_milliseconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.int32_milliseconds_larger_unit( - input=0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -117,7 +117,7 @@ async def test_query_int32_milliseconds_larger_unit(self, duration_endpoint): async def test_query_float_milliseconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.float_milliseconds( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -128,7 +128,7 @@ async def test_query_float_milliseconds(self, duration_endpoint): async def test_query_float_milliseconds_larger_unit(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.float_milliseconds_larger_unit( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -139,7 +139,7 @@ async def test_query_float_milliseconds_larger_unit(self, duration_endpoint): async def test_query_float64_milliseconds(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.float64_milliseconds( - input=0.0, + input="1 day, 0:00:00", ) # please add some check logic here by yourself @@ -150,7 +150,7 @@ async def test_query_float64_milliseconds(self, duration_endpoint): async def test_query_int32_seconds_array(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.int32_seconds_array( - input=[0], + input=["1 day, 0:00:00"], ) # please add some check logic here by yourself @@ -161,7 +161,7 @@ async def test_query_int32_seconds_array(self, duration_endpoint): async def test_query_int32_milliseconds_array(self, duration_endpoint): client = self.create_async_client(endpoint=duration_endpoint) response = await client.query.int32_milliseconds_array( - input=[0], + input=["1 day, 0:00:00"], ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/pyproject.toml index cfacfacc9557..d5e004cd7dff 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-duration/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/operations/_operations.py index aeee287165fb..cf87a3b9b4d3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/operations/_operations.py @@ -26,7 +26,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -36,7 +36,6 @@ ) from .._configuration import NumericClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -76,12 +75,12 @@ async def safeint_as_string( @overload async def safeint_as_string( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types.SafeintAsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.SafeintAsStringProperty: """safeint_as_string. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.types.SafeintAsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -108,12 +107,13 @@ async def safeint_as_string( @distributed_trace_async async def safeint_as_string( - self, value: Union[_models.SafeintAsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, value: Union[_models.SafeintAsStringProperty, _types.SafeintAsStringProperty, IO[bytes]], **kwargs: Any ) -> _models.SafeintAsStringProperty: """safeint_as_string. - :param value: Is one of the following types: SafeintAsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.models.SafeintAsStringProperty or JSON or IO[bytes] + :param value: Is either a SafeintAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.models.SafeintAsStringProperty or + ~encode.numeric.types.SafeintAsStringProperty or IO[bytes] :return: SafeintAsStringProperty. The SafeintAsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.models.SafeintAsStringProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -195,12 +195,12 @@ async def uint32_as_string_optional( @overload async def uint32_as_string_optional( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types.Uint32AsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Uint32AsStringProperty: """uint32_as_string_optional. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.types.Uint32AsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -227,12 +227,13 @@ async def uint32_as_string_optional( @distributed_trace_async async def uint32_as_string_optional( - self, value: Union[_models.Uint32AsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, value: Union[_models.Uint32AsStringProperty, _types.Uint32AsStringProperty, IO[bytes]], **kwargs: Any ) -> _models.Uint32AsStringProperty: """uint32_as_string_optional. - :param value: Is one of the following types: Uint32AsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.models.Uint32AsStringProperty or JSON or IO[bytes] + :param value: Is either a Uint32AsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.models.Uint32AsStringProperty or + ~encode.numeric.types.Uint32AsStringProperty or IO[bytes] :return: Uint32AsStringProperty. The Uint32AsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.models.Uint32AsStringProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -314,12 +315,12 @@ async def uint8_as_string( @overload async def uint8_as_string( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types.Uint8AsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Uint8AsStringProperty: """uint8_as_string. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.types.Uint8AsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -346,12 +347,13 @@ async def uint8_as_string( @distributed_trace_async async def uint8_as_string( - self, value: Union[_models.Uint8AsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, value: Union[_models.Uint8AsStringProperty, _types.Uint8AsStringProperty, IO[bytes]], **kwargs: Any ) -> _models.Uint8AsStringProperty: """uint8_as_string. - :param value: Is one of the following types: Uint8AsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.models.Uint8AsStringProperty or JSON or IO[bytes] + :param value: Is either a Uint8AsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.models.Uint8AsStringProperty or + ~encode.numeric.types.Uint8AsStringProperty or IO[bytes] :return: Uint8AsStringProperty. The Uint8AsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.models.Uint8AsStringProperty :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/operations/_operations.py index 712c2683080e..819e1bff3aab 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import NumericClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -125,12 +124,12 @@ def safeint_as_string( @overload def safeint_as_string( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types.SafeintAsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.SafeintAsStringProperty: """safeint_as_string. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.types.SafeintAsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -157,12 +156,13 @@ def safeint_as_string( @distributed_trace def safeint_as_string( - self, value: Union[_models.SafeintAsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, value: Union[_models.SafeintAsStringProperty, _types.SafeintAsStringProperty, IO[bytes]], **kwargs: Any ) -> _models.SafeintAsStringProperty: """safeint_as_string. - :param value: Is one of the following types: SafeintAsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.models.SafeintAsStringProperty or JSON or IO[bytes] + :param value: Is either a SafeintAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.models.SafeintAsStringProperty or + ~encode.numeric.types.SafeintAsStringProperty or IO[bytes] :return: SafeintAsStringProperty. The SafeintAsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.models.SafeintAsStringProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -244,12 +244,12 @@ def uint32_as_string_optional( @overload def uint32_as_string_optional( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types.Uint32AsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Uint32AsStringProperty: """uint32_as_string_optional. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.types.Uint32AsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -276,12 +276,13 @@ def uint32_as_string_optional( @distributed_trace def uint32_as_string_optional( - self, value: Union[_models.Uint32AsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, value: Union[_models.Uint32AsStringProperty, _types.Uint32AsStringProperty, IO[bytes]], **kwargs: Any ) -> _models.Uint32AsStringProperty: """uint32_as_string_optional. - :param value: Is one of the following types: Uint32AsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.models.Uint32AsStringProperty or JSON or IO[bytes] + :param value: Is either a Uint32AsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.models.Uint32AsStringProperty or + ~encode.numeric.types.Uint32AsStringProperty or IO[bytes] :return: Uint32AsStringProperty. The Uint32AsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.models.Uint32AsStringProperty :raises ~azure.core.exceptions.HttpResponseError: @@ -363,12 +364,12 @@ def uint8_as_string( @overload def uint8_as_string( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types.Uint8AsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Uint8AsStringProperty: """uint8_as_string. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.types.Uint8AsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -395,12 +396,13 @@ def uint8_as_string( @distributed_trace def uint8_as_string( - self, value: Union[_models.Uint8AsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, value: Union[_models.Uint8AsStringProperty, _types.Uint8AsStringProperty, IO[bytes]], **kwargs: Any ) -> _models.Uint8AsStringProperty: """uint8_as_string. - :param value: Is one of the following types: Uint8AsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.models.Uint8AsStringProperty or JSON or IO[bytes] + :param value: Is either a Uint8AsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.models.Uint8AsStringProperty or + ~encode.numeric.types.Uint8AsStringProperty or IO[bytes] :return: Uint8AsStringProperty. The Uint8AsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.models.Uint8AsStringProperty :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/encode/numeric/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/pyproject.toml index dffe466030ab..8c2df7d0a2a8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/encode-numeric/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_operations/_operations.py index 7033b36288ab..20d79c30c5dd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import RecursiveClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -87,11 +86,11 @@ def put(self, input: _models.Extension, *, content_type: str = "application/json """ @overload - def put(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, input: _types.Extension, *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param input: Required. - :type input: JSON + :type input: ~generation.subdir._generated.types.Extension :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -116,12 +115,13 @@ def put(self, input: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Extension, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Extension, _types.Extension, IO[bytes]], **kwargs: Any ) -> None: """put. - :param input: Is one of the following types: Extension, JSON, IO[bytes] Required. - :type input: ~generation.subdir._generated.models.Extension or JSON or IO[bytes] + :param input: Is either a Extension type or a IO[bytes] type. Required. + :type input: ~generation.subdir._generated.models.Extension or + ~generation.subdir._generated.types.Extension or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/aio/_operations/_operations.py index 738862bc83d0..6ddef53f5e43 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/aio/_operations/_operations.py @@ -27,13 +27,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_recursive_get_request, build_recursive_put_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import RecursiveClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -57,11 +56,11 @@ async def put(self, input: _models.Extension, *, content_type: str = "applicatio """ @overload - async def put(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, input: _types.Extension, *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param input: Required. - :type input: JSON + :type input: ~generation.subdir._generated.types.Extension :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -85,11 +84,12 @@ async def put(self, input: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, input: Union[_models.Extension, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, input: Union[_models.Extension, _types.Extension, IO[bytes]], **kwargs: Any) -> None: """put. - :param input: Is one of the following types: Extension, JSON, IO[bytes] Required. - :type input: ~generation.subdir._generated.models.Extension or JSON or IO[bytes] + :param input: Is either a Extension type or a IO[bytes] type. Required. + :type input: ~generation.subdir._generated.models.Extension or + ~generation.subdir._generated.types.Extension or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/first/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/types.py similarity index 61% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/first/types.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/types.py index 52f34644d3eb..4dfb93b9fdb3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-namespace/client/clientnamespace/first/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/generation/subdir/_generated/types.py @@ -9,12 +9,24 @@ from typing_extensions import Required, TypedDict -class FirstClientResult(TypedDict, total=False): - """FirstClientResult. +class Element(TypedDict, total=False): + """element. - :ivar name: Required. - :vartype name: str + :ivar extension: + :vartype extension: list["Extension"] """ - name: Required[str] + extension: list["Extension"] + + +class Extension(Element): + """extension. + + :ivar extension: + :vartype extension: list["Extension"] + :ivar level: Required. + :vartype level: int + """ + + level: Required[int] """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/pyproject.toml index 28afd8f80930..d352b0706487 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/aio/operations/_operations.py index b06fa295fa58..0c5d600fa172 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ..._utils.utils import ClientMixinABC @@ -39,7 +39,6 @@ ) from .._configuration import AddedClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -79,12 +78,12 @@ async def v2_in_interface( @overload async def v2_in_interface( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV2: """v2_in_interface. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -115,11 +114,14 @@ async def v2_in_interface( params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - async def v2_in_interface(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + async def v2_in_interface( + self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV2 or + ~generation.subdir2._generated.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~generation.subdir2._generated.models.ModelV2 :raises ~azure.core.exceptions.HttpResponseError: @@ -209,12 +211,12 @@ async def v1( @overload async def v1( - self, body: JSON, *, header_v2: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV1, *, header_v2: str, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV1: """v1. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV1 :keyword header_v2: Required. :paramtype header_v2: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -249,12 +251,13 @@ async def v1( api_versions_list=["v1", "v2"], ) async def v1( - self, body: Union[_models.ModelV1, JSON, IO[bytes]], *, header_v2: str, **kwargs: Any + self, body: Union[_models.ModelV1, _types.ModelV1, IO[bytes]], *, header_v2: str, **kwargs: Any ) -> _models.ModelV1: """v1. - :param body: Is one of the following types: ModelV1, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV1 or JSON or IO[bytes] + :param body: Is either a ModelV1 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV1 or + ~generation.subdir2._generated.types.ModelV1 or IO[bytes] :keyword header_v2: Required. :paramtype header_v2: str :return: ModelV1. The ModelV1 is compatible with MutableMapping @@ -339,11 +342,13 @@ async def v2( """ @overload - async def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + async def v2( + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -372,11 +377,12 @@ async def v2(self, body: IO[bytes], *, content_type: str = "application/json", * params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - async def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + async def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV2 or + ~generation.subdir2._generated.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~generation.subdir2._generated.models.ModelV2 :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/models/_models.py index 1c69159c9108..fb3eb408a46e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/models/_models.py @@ -12,7 +12,7 @@ from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - from .. import _types, models as _models + from .. import _unions, models as _models class ModelV1(_Model): @@ -32,7 +32,7 @@ class ModelV1(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Known values are: \"enumMemberV1\" and \"enumMemberV2\".""" - union_prop: "_types.UnionV1" = rest_field( + union_prop: "_unions.UnionV1" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a int type.""" @@ -43,7 +43,7 @@ def __init__( *, prop: str, enum_prop: Union[str, "_models.EnumV1"], - union_prop: "_types.UnionV1", + union_prop: "_unions.UnionV1", ) -> None: ... @overload @@ -74,7 +74,7 @@ class ModelV2(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. \"enumMember\"""" - union_prop: "_types.UnionV2" = rest_field( + union_prop: "_unions.UnionV2" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a int type.""" @@ -85,7 +85,7 @@ def __init__( *, prop: str, enum_prop: Union[str, "_models.EnumV2"], - union_prop: "_types.UnionV2", + union_prop: "_unions.UnionV2", ) -> None: ... @overload diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/operations/_operations.py index 60784a48d94d..294ade90fc52 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/operations/_operations.py @@ -26,14 +26,13 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import AddedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer from .._utils.utils import ClientMixinABC from .._validation import api_version_validation -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -127,11 +126,13 @@ def v2_in_interface( """ @overload - def v2_in_interface(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + def v2_in_interface( + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -162,11 +163,14 @@ def v2_in_interface( params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - def v2_in_interface(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + def v2_in_interface( + self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV2 or + ~generation.subdir2._generated.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~generation.subdir2._generated.models.ModelV2 :raises ~azure.core.exceptions.HttpResponseError: @@ -254,12 +258,12 @@ def v1( @overload def v1( - self, body: JSON, *, header_v2: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV1, *, header_v2: str, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV1: """v1. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV1 :keyword header_v2: Required. :paramtype header_v2: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -293,11 +297,14 @@ def v1( params_added_on={"v2": ["header_v2"]}, api_versions_list=["v1", "v2"], ) - def v1(self, body: Union[_models.ModelV1, JSON, IO[bytes]], *, header_v2: str, **kwargs: Any) -> _models.ModelV1: + def v1( + self, body: Union[_models.ModelV1, _types.ModelV1, IO[bytes]], *, header_v2: str, **kwargs: Any + ) -> _models.ModelV1: """v1. - :param body: Is one of the following types: ModelV1, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV1 or JSON or IO[bytes] + :param body: Is either a ModelV1 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV1 or + ~generation.subdir2._generated.types.ModelV1 or IO[bytes] :keyword header_v2: Required. :paramtype header_v2: str :return: ModelV1. The ModelV1 is compatible with MutableMapping @@ -380,11 +387,11 @@ def v2(self, body: _models.ModelV2, *, content_type: str = "application/json", * """ @overload - def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + def v2(self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -413,11 +420,12 @@ def v2(self, body: IO[bytes], *, content_type: str = "application/json", **kwarg params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV2 or + ~generation.subdir2._generated.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~generation.subdir2._generated.models.ModelV2 :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/types.py index e9a96d5f28ed..4d12103c76c8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/generation/subdir2/_generated/types.py @@ -20,9 +20,9 @@ class ModelV1(TypedDict, total=False): :ivar prop: Required. :vartype prop: str :ivar enum_prop: Required. Known values are: "enumMemberV1" and "enumMemberV2". - :vartype enum_prop: str or ~generation.subdir2.models.EnumV1 + :vartype enum_prop: Union[str, "EnumV1"] :ivar union_prop: Required. Is either a str type or a int type. - :vartype union_prop: str or int + :vartype union_prop: "_unions.UnionV1" """ prop: Required[str] @@ -39,9 +39,9 @@ class ModelV2(TypedDict, total=False): :ivar prop: Required. :vartype prop: str :ivar enum_prop: Required. "enumMember" - :vartype enum_prop: str or ~generation.subdir2.models.EnumV2 + :vartype enum_prop: Union[str, "EnumV2"] :ivar union_prop: Required. Is either a str type or a int type. - :vartype union_prop: str or int + :vartype union_prop: "_unions.UnionV2" """ prop: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/pyproject.toml index 515ad289d2a0..79feaaad4b71 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/generation-subdir2/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_operations/_operations.py index 73dd523779e8..f1a577763e93 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import VisibilityClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -176,12 +175,12 @@ def get_model( @overload def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -212,12 +211,17 @@ def get_model( @distributed_trace def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -304,12 +308,12 @@ def head_model( @overload def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> None: """head_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -340,12 +344,17 @@ def head_model( @distributed_trace def head_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> None: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: None @@ -416,11 +425,13 @@ def put_model( """ @overload - def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -445,12 +456,13 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", @distributed_trace def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -518,11 +530,13 @@ def patch_model( """ @overload - def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -547,12 +561,13 @@ def patch_model(self, input: IO[bytes], *, content_type: str = "application/json @distributed_trace def patch_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -620,11 +635,13 @@ def post_model( """ @overload - def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -649,12 +666,13 @@ def post_model(self, input: IO[bytes], *, content_type: str = "application/json" @distributed_trace def post_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -722,11 +740,13 @@ def delete_model( """ @overload - def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -751,12 +771,13 @@ def delete_model(self, input: IO[bytes], *, content_type: str = "application/jso @distributed_trace def delete_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -825,12 +846,12 @@ def put_read_only_model( @overload def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -857,12 +878,13 @@ def put_read_only_model( @distributed_trace def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.ReadOnlyModel or + ~headasbooleanfalse.types.ReadOnlyModel or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~headasbooleanfalse.models.ReadOnlyModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_operations/_operations.py index 4bd319c6919b..443c2760f9da 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_visibility_delete_model_request, build_visibility_get_model_request, @@ -41,7 +41,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import VisibilityClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -70,12 +69,12 @@ async def get_model( @overload async def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -106,12 +105,17 @@ async def get_model( @distributed_trace_async async def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -198,12 +202,12 @@ async def head_model( @overload async def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> None: """head_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -234,12 +238,17 @@ async def head_model( @distributed_trace_async async def head_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> None: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: None @@ -310,11 +319,13 @@ async def put_model( """ @overload - async def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -338,11 +349,14 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def put_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -410,11 +424,13 @@ async def patch_model( """ @overload - async def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -438,11 +454,14 @@ async def patch_model(self, input: IO[bytes], *, content_type: str = "applicatio """ @distributed_trace_async - async def patch_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -510,11 +529,13 @@ async def post_model( """ @overload - async def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -538,11 +559,14 @@ async def post_model(self, input: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def post_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def post_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -610,11 +634,13 @@ async def delete_model( """ @overload - async def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -638,11 +664,14 @@ async def delete_model(self, input: IO[bytes], *, content_type: str = "applicati """ @distributed_trace_async - async def delete_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def delete_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -711,12 +740,12 @@ async def put_read_only_model( @overload async def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -743,12 +772,13 @@ async def put_read_only_model( @distributed_trace_async async def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.ReadOnlyModel or + ~headasbooleanfalse.types.ReadOnlyModel or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~headasbooleanfalse.models.ReadOnlyModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/headasbooleanfalse/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/pyproject.toml index 18bb93d42ece..88fad79735b6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleanfalse/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_operations/_operations.py index 37a192ac33db..4e370d2d069c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import VisibilityClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -176,12 +175,12 @@ def get_model( @overload def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -212,12 +211,17 @@ def get_model( @distributed_trace def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -304,12 +308,12 @@ def head_model( @overload def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> bool: """head_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -340,12 +344,17 @@ def head_model( @distributed_trace def head_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> bool: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: bool @@ -417,11 +426,13 @@ def put_model( """ @overload - def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -446,12 +457,13 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", @distributed_trace def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -519,11 +531,13 @@ def patch_model( """ @overload - def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -548,12 +562,13 @@ def patch_model(self, input: IO[bytes], *, content_type: str = "application/json @distributed_trace def patch_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -621,11 +636,13 @@ def post_model( """ @overload - def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -650,12 +667,13 @@ def post_model(self, input: IO[bytes], *, content_type: str = "application/json" @distributed_trace def post_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -723,11 +741,13 @@ def delete_model( """ @overload - def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -752,12 +772,13 @@ def delete_model(self, input: IO[bytes], *, content_type: str = "application/jso @distributed_trace def delete_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -826,12 +847,12 @@ def put_read_only_model( @overload def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -858,12 +879,13 @@ def put_read_only_model( @distributed_trace def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.ReadOnlyModel or ~headasbooleantrue.types.ReadOnlyModel + or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~headasbooleantrue.models.ReadOnlyModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_operations/_operations.py index 148b94d55047..5f1540e4ccd0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_visibility_delete_model_request, build_visibility_get_model_request, @@ -41,7 +41,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import VisibilityClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -70,12 +69,12 @@ async def get_model( @overload async def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -106,12 +105,17 @@ async def get_model( @distributed_trace_async async def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -198,12 +202,12 @@ async def head_model( @overload async def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> bool: """head_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -234,12 +238,17 @@ async def head_model( @distributed_trace_async async def head_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> bool: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: bool @@ -311,11 +320,13 @@ async def put_model( """ @overload - async def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -339,11 +350,14 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def put_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -411,11 +425,13 @@ async def patch_model( """ @overload - async def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -439,11 +455,14 @@ async def patch_model(self, input: IO[bytes], *, content_type: str = "applicatio """ @distributed_trace_async - async def patch_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -511,11 +530,13 @@ async def post_model( """ @overload - async def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -539,11 +560,14 @@ async def post_model(self, input: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def post_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def post_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -611,11 +635,13 @@ async def delete_model( """ @overload - async def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -639,11 +665,14 @@ async def delete_model(self, input: IO[bytes], *, content_type: str = "applicati """ @distributed_trace_async - async def delete_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def delete_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -712,12 +741,12 @@ async def put_read_only_model( @overload async def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -744,12 +773,13 @@ async def put_read_only_model( @distributed_trace_async async def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.ReadOnlyModel or ~headasbooleantrue.types.ReadOnlyModel + or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~headasbooleantrue.models.ReadOnlyModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/headasbooleantrue/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/pyproject.toml index 3191eecc665c..4673c18403bb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/headasbooleantrue/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/operations/_operations.py index 7b64ea5c882d..d682d6226ce9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/operations/_operations.py @@ -24,15 +24,15 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import build_explicit_body_simple_request, build_implicit_body_simple_request from .._configuration import BasicClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] _Unset: Any = object() @@ -68,11 +68,11 @@ async def simple(self, body: _models.User, *, content_type: str = "application/j """ @overload - async def simple(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def simple(self, body: _types.User, *, content_type: str = "application/json", **kwargs: Any) -> None: """simple. :param body: Required. - :type body: JSON + :type body: ~parameters.basic.types.User :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -96,11 +96,11 @@ async def simple(self, body: IO[bytes], *, content_type: str = "application/json """ @distributed_trace_async - async def simple(self, body: Union[_models.User, JSON, IO[bytes]], **kwargs: Any) -> None: + async def simple(self, body: Union[_models.User, _types.User, IO[bytes]], **kwargs: Any) -> None: """simple. - :param body: Is one of the following types: User, JSON, IO[bytes] Required. - :type body: ~parameters.basic.models.User or JSON or IO[bytes] + :param body: Is either a User type or a IO[bytes] type. Required. + :type body: ~parameters.basic.models.User or ~parameters.basic.types.User or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -184,11 +184,13 @@ async def simple(self, *, name: str, content_type: str = "application/json", **k """ @overload - async def simple(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def simple( + self, body: _types.SimpleRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """simple. :param body: Required. - :type body: JSON + :type body: ~parameters.basic.types.SimpleRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -212,11 +214,13 @@ async def simple(self, body: IO[bytes], *, content_type: str = "application/json """ @distributed_trace_async - async def simple(self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any) -> None: + async def simple( + self, body: Union[JSON, _types.SimpleRequest, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + ) -> None: """simple. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SimpleRequest, IO[bytes] Required. + :type body: JSON or ~parameters.basic.types.SimpleRequest or IO[bytes] :keyword name: Required. :paramtype name: str :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/operations/_operations.py index 52ad8a9b5f60..ce22b375866e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/operations/_operations.py @@ -24,14 +24,14 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import BasicClientConfiguration from .._utils.model_base import SdkJSONEncoder from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] _Unset: Any = object() _SERIALIZER = Serializer() @@ -98,11 +98,11 @@ def simple(self, body: _models.User, *, content_type: str = "application/json", """ @overload - def simple(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def simple(self, body: _types.User, *, content_type: str = "application/json", **kwargs: Any) -> None: """simple. :param body: Required. - :type body: JSON + :type body: ~parameters.basic.types.User :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -127,12 +127,12 @@ def simple(self, body: IO[bytes], *, content_type: str = "application/json", **k @distributed_trace def simple( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.User, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.User, _types.User, IO[bytes]], **kwargs: Any ) -> None: """simple. - :param body: Is one of the following types: User, JSON, IO[bytes] Required. - :type body: ~parameters.basic.models.User or JSON or IO[bytes] + :param body: Is either a User type or a IO[bytes] type. Required. + :type body: ~parameters.basic.models.User or ~parameters.basic.types.User or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -216,11 +216,11 @@ def simple(self, *, name: str, content_type: str = "application/json", **kwargs: """ @overload - def simple(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def simple(self, body: _types.SimpleRequest, *, content_type: str = "application/json", **kwargs: Any) -> None: """simple. :param body: Required. - :type body: JSON + :type body: ~parameters.basic.types.SimpleRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -245,12 +245,12 @@ def simple(self, body: IO[bytes], *, content_type: str = "application/json", **k @distributed_trace def simple( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, body: Union[JSON, _types.SimpleRequest, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any ) -> None: """simple. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SimpleRequest, IO[bytes] Required. + :type body: JSON or ~parameters.basic.types.SimpleRequest or IO[bytes] :keyword name: Required. :paramtype name: str :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/types.py index 7c63b904b210..09b5b2ba8c44 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/parameters/basic/types.py @@ -18,3 +18,14 @@ class User(TypedDict, total=False): name: Required[str] """Required.""" + + +class SimpleRequest(TypedDict, total=False): + """SimpleRequest. + + :ivar name: Required. + :vartype name: str + """ + + name: Required[str] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/pyproject.toml index b7ff6a05b659..be3301c3cbda 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-basic/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_operations/_operations.py index 00d46a0c5d07..f5688fd5efc2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_operations/_operations.py @@ -24,7 +24,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from .._configuration import BodyOptionalityClientConfiguration from .._utils.model_base import SdkJSONEncoder from .._utils.serialization import Serializer @@ -88,11 +88,13 @@ def required_explicit( """ @overload - def required_explicit(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def required_explicit( + self, body: _types_models1.BodyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """required_explicit. :param body: Required. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -117,12 +119,13 @@ def required_explicit(self, body: IO[bytes], *, content_type: str = "application @distributed_trace def required_explicit( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.BodyModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.BodyModel, _types_models1.BodyModel, IO[bytes]], **kwargs: Any ) -> None: """required_explicit. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Required. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Required. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -188,11 +191,13 @@ def required_implicit(self, *, name: str, content_type: str = "application/json" """ @overload - def required_implicit(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def required_implicit( + self, body: _types_models1.BodyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """required_implicit. :param body: Required. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -217,12 +222,12 @@ def required_implicit(self, body: IO[bytes], *, content_type: str = "application @distributed_trace def required_implicit( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, body: Union[JSON, _types_models1.BodyModel, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any ) -> None: """required_implicit. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BodyModel, IO[bytes] Required. + :type body: JSON or ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :keyword name: Required. :paramtype name: str :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_operations.py index 12fdffe9dbab..eb2bd8083d8c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_operations.py @@ -25,7 +25,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..._operations._operations import ( build_body_optionality_required_explicit_request, build_body_optionality_required_implicit_request, @@ -61,11 +61,13 @@ async def required_explicit( """ @overload - async def required_explicit(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def required_explicit( + self, body: _types_models2.BodyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """required_explicit. :param body: Required. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -91,11 +93,14 @@ async def required_explicit( """ @distributed_trace_async - async def required_explicit(self, body: Union[_models2.BodyModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def required_explicit( + self, body: Union[_models2.BodyModel, _types_models2.BodyModel, IO[bytes]], **kwargs: Any + ) -> None: """required_explicit. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Required. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Required. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -161,11 +166,13 @@ async def required_implicit(self, *, name: str, content_type: str = "application """ @overload - async def required_implicit(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def required_implicit( + self, body: _types_models2.BodyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """required_implicit. :param body: Required. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -192,12 +199,12 @@ async def required_implicit( @distributed_trace_async async def required_implicit( - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, body: Union[JSON, _types_models2.BodyModel, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any ) -> None: """required_implicit. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BodyModel, IO[bytes] Required. + :type body: JSON or ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :keyword name: Required. :paramtype name: str :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_operations.py index b198869a0213..b32433ef8936 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_operations.py @@ -24,13 +24,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from .... import models as _models3 +from .... import models as _models3, types as _types_models3 from ...._utils.model_base import SdkJSONEncoder from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import BodyOptionalityClientConfiguration from ...operations._operations import build_optional_explicit_omit_request, build_optional_explicit_set_request -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -69,11 +68,13 @@ async def set( """ @overload - async def set(self, body: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def set( + self, body: Optional[_types_models3.BodyModel] = None, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """set. :param body: Default value is None. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -99,11 +100,14 @@ async def set( """ @distributed_trace_async - async def set(self, body: Optional[Union[_models3.BodyModel, JSON, IO[bytes]]] = None, **kwargs: Any) -> None: + async def set( + self, body: Optional[Union[_models3.BodyModel, _types_models3.BodyModel, IO[bytes]]] = None, **kwargs: Any + ) -> None: """set. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Default value is None. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Default value is None. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -175,11 +179,13 @@ async def omit( """ @overload - async def omit(self, body: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def omit( + self, body: Optional[_types_models3.BodyModel] = None, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """omit. :param body: Default value is None. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -205,11 +211,14 @@ async def omit( """ @distributed_trace_async - async def omit(self, body: Optional[Union[_models3.BodyModel, JSON, IO[bytes]]] = None, **kwargs: Any) -> None: + async def omit( + self, body: Optional[Union[_models3.BodyModel, _types_models3.BodyModel, IO[bytes]]] = None, **kwargs: Any + ) -> None: """omit. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Default value is None. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Default value is None. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_operations.py index abb6c87c170d..7242039aad54 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_operations.py @@ -24,12 +24,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..._configuration import BodyOptionalityClientConfiguration from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -99,11 +98,13 @@ def set( """ @overload - def set(self, body: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any) -> None: + def set( + self, body: Optional[_types_models2.BodyModel] = None, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """set. :param body: Default value is None. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -128,12 +129,13 @@ def set(self, body: Optional[IO[bytes]] = None, *, content_type: str = "applicat @distributed_trace def set( # pylint: disable=inconsistent-return-statements - self, body: Optional[Union[_models2.BodyModel, JSON, IO[bytes]]] = None, **kwargs: Any + self, body: Optional[Union[_models2.BodyModel, _types_models2.BodyModel, IO[bytes]]] = None, **kwargs: Any ) -> None: """set. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Default value is None. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Default value is None. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -205,11 +207,13 @@ def omit( """ @overload - def omit(self, body: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any) -> None: + def omit( + self, body: Optional[_types_models2.BodyModel] = None, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """omit. :param body: Default value is None. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -234,12 +238,13 @@ def omit(self, body: Optional[IO[bytes]] = None, *, content_type: str = "applica @distributed_trace def omit( # pylint: disable=inconsistent-return-statements - self, body: Optional[Union[_models2.BodyModel, JSON, IO[bytes]]] = None, **kwargs: Any + self, body: Optional[Union[_models2.BodyModel, _types_models2.BodyModel, IO[bytes]]] = None, **kwargs: Any ) -> None: """omit. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Default value is None. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Default value is None. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/pyproject.toml index 669bd4bba38f..c8b1f2a3f2d2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-optionality/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/CHANGELOG.md new file mode 100644 index 000000000000..b957b2575b48 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (1970-01-01) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/LICENSE b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/MANIFEST.in b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/MANIFEST.in new file mode 100644 index 000000000000..d4bf7087fae0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/MANIFEST.in @@ -0,0 +1,6 @@ +include *.md +include LICENSE +include parameters/bodyroot/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include parameters/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/README.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/_metadata.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/_metadata.json new file mode 100644 index 000000000000..49515fdbafdf --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/_metadata.json @@ -0,0 +1,3 @@ +{ + "apiVersions": {} +} \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/apiview-properties.json new file mode 100644 index 000000000000..c70f81ae24b5 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/apiview-properties.json @@ -0,0 +1,10 @@ +{ + "CrossLanguagePackageId": "Parameters.BodyRoot", + "CrossLanguageDefinitionId": { + "parameters.bodyroot.models.BodyRootModel": "Parameters.BodyRoot.BodyRootModel", + "parameters.bodyroot.models.NestedParameterBody": "Parameters.BodyRoot.nested.Parameter.body.anonymous", + "parameters.bodyroot.BodyRootClient.nested": "Parameters.BodyRoot.nested", + "parameters.bodyroot.aio.BodyRootClient.nested": "Parameters.BodyRoot.nested" + }, + "CrossLanguageVersion": "1b93bc1e60f7" +} \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/dev_requirements.txt b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/dev_requirements.txt new file mode 100644 index 000000000000..0e53b6a72db5 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/dev_requirements.txt @@ -0,0 +1,3 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +aiohttp \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/conftest.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/conftest.py new file mode 100644 index 000000000000..bb527696c365 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + bodyroot_subscription_id = os.environ.get("BODYROOT_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + bodyroot_tenant_id = os.environ.get("BODYROOT_TENANT_ID", "00000000-0000-0000-0000-000000000000") + bodyroot_client_id = os.environ.get("BODYROOT_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + bodyroot_client_secret = os.environ.get("BODYROOT_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=bodyroot_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=bodyroot_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=bodyroot_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=bodyroot_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/test_body_root.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/test_body_root.py new file mode 100644 index 000000000000..7e69724eeecf --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/test_body_root.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import BodyRootClientTestBase, BodyRootPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestBodyRoot(BodyRootClientTestBase): + @BodyRootPreparer() + @recorded_by_proxy + def test_nested(self, bodyroot_endpoint): + client = self.create_client(endpoint=bodyroot_endpoint) + response = client.nested( + body_root_parameters={"category": "str", "linkType": "str", "wasSuccessful": bool}, + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/test_body_root_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/test_body_root_async.py new file mode 100644 index 000000000000..f4c3fd34667f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/test_body_root_async.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import BodyRootPreparer +from testpreparer_async import BodyRootClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestBodyRootAsync(BodyRootClientTestBaseAsync): + @BodyRootPreparer() + @recorded_by_proxy_async + async def test_nested(self, bodyroot_endpoint): + client = self.create_async_client(endpoint=bodyroot_endpoint) + response = await client.nested( + body_root_parameters={"category": "str", "linkType": "str", "wasSuccessful": bool}, + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/testpreparer.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/testpreparer.py new file mode 100644 index 000000000000..f180e966cedb --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/testpreparer.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer +import functools +from parameters.bodyroot import BodyRootClient + + +class BodyRootClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(BodyRootClient) + return self.create_client_from_credential( + BodyRootClient, + credential=credential, + endpoint=endpoint, + ) + + +BodyRootPreparer = functools.partial( + PowerShellPreparer, "bodyroot", bodyroot_endpoint="https://fake_bodyroot_endpoint.com" +) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/testpreparer_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/testpreparer_async.py new file mode 100644 index 000000000000..2820b84ee8a9 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/generated_tests/testpreparer_async.py @@ -0,0 +1,20 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from devtools_testutils import AzureRecordedTestCase +from parameters.bodyroot.aio import BodyRootClient + + +class BodyRootClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(BodyRootClient, is_async=True) + return self.create_client_from_credential( + BodyRootClient, + credential=credential, + endpoint=endpoint, + ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/__init__.py new file mode 100644 index 000000000000..829491da6506 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import BodyRootClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BodyRootClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_client.py new file mode 100644 index 000000000000..59f32a0055ee --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_client.py @@ -0,0 +1,97 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +import sys +from typing import Any + +from azure.core import PipelineClient +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse + +from ._configuration import BodyRootClientConfiguration +from ._operations import _BodyRootClientOperationsMixin +from ._utils.serialization import Deserializer, Serializer + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + + +class BodyRootClient(_BodyRootClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """Test for @bodyRoot parameter patterns. + + :keyword endpoint: Service host. Default value is "http://localhost:3000". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "http://localhost:3000", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = BodyRootClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_configuration.py new file mode 100644 index 000000000000..4181dd011652 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_configuration.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any + +from azure.core.pipeline import policies + +from ._version import VERSION + + +class BodyRootClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for BodyRootClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "http://localhost:3000". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "parameters-bodyroot/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_operations/__init__.py similarity index 88% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_operations/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_operations/__init__.py index 80532a9c6f3d..f3d1d8253829 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/aio/_operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_operations/__init__.py @@ -12,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import _RenamedOperationClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import _BodyRootClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_operations/_operations.py new file mode 100644 index 000000000000..af61cad08597 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_operations/_operations.py @@ -0,0 +1,161 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models, types as _types +from .._configuration import BodyRootClientConfiguration +from .._utils.model_base import SdkJSONEncoder +from .._utils.serialization import Serializer +from .._utils.utils import ClientMixinABC + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_body_root_nested_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/parameters/body-root/nested" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +class _BodyRootClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], BodyRootClientConfiguration] +): + + @overload + def nested( + self, body_root_parameters: _models.BodyRootModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: ~parameters.bodyroot.models.BodyRootModel + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def nested( + self, body_root_parameters: _types.BodyRootModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: ~parameters.bodyroot.types.BodyRootModel + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def nested(self, body_root_parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def nested( # pylint: disable=inconsistent-return-statements + self, body_root_parameters: Union[_models.BodyRootModel, _types.BodyRootModel, IO[bytes]], **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Is either a BodyRootModel type or a IO[bytes] type. Required. + :type body_root_parameters: ~parameters.bodyroot.models.BodyRootModel or + ~parameters.bodyroot.types.BodyRootModel or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body_root_parameters, (IOBase, bytes)): + _content = body_root_parameters + else: + _content = json.dumps(body_root_parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_body_root_nested_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/model_base.py new file mode 100644 index 000000000000..0f2c5bdfe70f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/model_base.py @@ -0,0 +1,1771 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null + +from azure.core.rest import HttpResponse + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on the mapping's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on the mapping's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: a set-like object providing a view on the mapping's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: The value for key if key is in the dictionary, else default. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if the dictionary is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from the dictionary. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Update the dictionary from a mapping or an iterable of key-value pairs. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: The value for key if key is in the dictionary, else default. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _serialize_duration(o, format) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass: dict[str, typing.Any] = {} + if args: + if isinstance(args[0], ET.Element): + dict_to_pass.update(self._init_from_xml(args[0])) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) + super().__init__(dict_to_pass) + + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + self, element: ET.Element + ) -> dict[str, typing.Any]: + """Deserialize an XML element into a dict mapping rest field names to values. + + :param ET.Element element: The XML element to deserialize from. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + existed_attr_keys: list[str] = [] + + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value.text if isinstance(value, ET.Element) else value) + except ValueError: + # for unknown value, return raw value + return value.text if isinstance(value, ET.Element) else value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +# pylint: disable=too-many-instance-attributes +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._is_optional = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + self._deserializer = deserializer + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + deserializer=deserializer, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) + wrapped_element = _create_xml_element( + element_name, + model_meta.get("prefix"), + _model_ns, + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + _set_xml_attribute(wrapped_element, k, v, prop_meta) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": _dict_ns, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": _items_ns, + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + _safe_register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/serialization.py new file mode 100644 index 000000000000..75906e2eb77f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/serialization.py @@ -0,0 +1,2175 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_utils/utils.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/utils.py similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/azure-client-generator-core-client-initialization/specs/azure/clientgenerator/core/clientinitialization/_utils/utils.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_utils/utils.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_version.py similarity index 85% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_types.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_version.py index ad0f62c5c369..be71c81bd282 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/_version.py @@ -6,7 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Union - -UnionV2 = Union[str, int] -UnionV1 = Union[str, int] +VERSION = "1.0.0b1" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/__init__.py new file mode 100644 index 000000000000..ddc896ebcbbf --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import BodyRootClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BodyRootClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_client.py new file mode 100644 index 000000000000..024bdd28aac3 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_client.py @@ -0,0 +1,99 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +import sys +from typing import Any, Awaitable + +from azure.core import AsyncPipelineClient +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest + +from .._utils.serialization import Deserializer, Serializer +from ._configuration import BodyRootClientConfiguration +from ._operations import _BodyRootClientOperationsMixin + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + + +class BodyRootClient(_BodyRootClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """Test for @bodyRoot parameter patterns. + + :keyword endpoint: Service host. Default value is "http://localhost:3000". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "http://localhost:3000", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = BodyRootClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_configuration.py new file mode 100644 index 000000000000..67c135c95a97 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_configuration.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any + +from azure.core.pipeline import policies + +from .._version import VERSION + + +class BodyRootClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for BodyRootClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "http://localhost:3000". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "parameters-bodyroot/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_operations/__init__.py similarity index 88% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_operations/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_operations/__init__.py index 80532a9c6f3d..f3d1d8253829 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/client-structure-renamedoperation/client/structure/renamedoperation/_operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_operations/__init__.py @@ -12,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import _RenamedOperationClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import _BodyRootClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_operations/_operations.py new file mode 100644 index 000000000000..620cdd3ac6f8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_operations/_operations.py @@ -0,0 +1,147 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models, types as _types +from ..._operations._operations import build_body_root_nested_request +from ..._utils.model_base import SdkJSONEncoder +from ..._utils.utils import ClientMixinABC +from .._configuration import BodyRootClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class _BodyRootClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], BodyRootClientConfiguration] +): + + @overload + async def nested( + self, body_root_parameters: _models.BodyRootModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: ~parameters.bodyroot.models.BodyRootModel + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def nested( + self, body_root_parameters: _types.BodyRootModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: ~parameters.bodyroot.types.BodyRootModel + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def nested( + self, body_root_parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def nested( + self, body_root_parameters: Union[_models.BodyRootModel, _types.BodyRootModel, IO[bytes]], **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Is either a BodyRootModel type or a IO[bytes] type. Required. + :type body_root_parameters: ~parameters.bodyroot.models.BodyRootModel or + ~parameters.bodyroot.types.BodyRootModel or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body_root_parameters, (IOBase, bytes)): + _content = body_root_parameters + else: + _content = json.dumps(body_root_parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_body_root_nested_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/models/__init__.py new file mode 100644 index 000000000000..00ff113cb52e --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/models/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + BodyRootModel, + NestedParameterBody, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BodyRootModel", + "NestedParameterBody", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/models/_models.py new file mode 100644 index 000000000000..50b44a53476a --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/models/_models.py @@ -0,0 +1,82 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +from typing import Any, Mapping, Optional, TYPE_CHECKING, overload + +from .._utils.model_base import Model as _Model, rest_field + +if TYPE_CHECKING: + from .. import models as _models + + +class BodyRootModel(_Model): + """BodyRootModel. + + :ivar category: + :vartype category: str + :ivar link_type: + :vartype link_type: str + :ivar was_successful: + :vartype was_successful: bool + """ + + category: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + link_type: Optional[str] = rest_field(name="linkType", visibility=["read", "create", "update", "delete", "query"]) + was_successful: Optional[bool] = rest_field( + name="wasSuccessful", visibility=["read", "create", "update", "delete", "query"] + ) + + @overload + def __init__( + self, + *, + category: Optional[str] = None, + link_type: Optional[str] = None, + was_successful: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NestedParameterBody(_Model): + """NestedParameterBody. + + :ivar body_root_parameters: Required. + :vartype body_root_parameters: ~parameters.bodyroot.models.BodyRootModel + """ + + body_root_parameters: "_models.BodyRootModel" = rest_field( + name="bodyRootParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Required.""" + + @overload + def __init__( + self, + *, + body_root_parameters: "_models.BodyRootModel", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/py.typed b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/types.py similarity index 52% rename from eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/types.py rename to eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/types.py index f478cd12cf0b..f672c653f71a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/parameters/bodyroot/types.py @@ -6,29 +6,31 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING from typing_extensions import Required, TypedDict -if TYPE_CHECKING: - from ..types import Pet +class BodyRootModel(TypedDict, total=False): + """BodyRootModel. -class NestedLinkResponseNestedItems(TypedDict, total=False): - """NestedLinkResponseNestedItems. - - :ivar pets: Required. - :vartype pets: list[~payload.pageable.models.Pet] + :ivar category: + :vartype category: str + :ivar link_type: + :vartype link_type: str + :ivar was_successful: + :vartype was_successful: bool """ - pets: Required[list["Pet"]] - """Required.""" + category: str + linkType: str + wasSuccessful: bool -class NestedLinkResponseNestedNext(TypedDict, total=False): - """NestedLinkResponseNestedNext. +class NestedParameterBody(TypedDict, total=False): + """NestedParameterBody. - :ivar next: - :vartype next: str + :ivar body_root_parameters: Required. + :vartype body_root_parameters: "BodyRootModel" """ - next: str + bodyRootParameters: Required["BodyRootModel"] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/pyproject.toml new file mode 100644 index 000000000000..80f43991681f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-body-root/pyproject.toml @@ -0,0 +1,60 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "parameters-bodyroot" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Corporation Azure Parameters Bodyroot Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", +] +requires-python = ">=3.10" +keywords = ["azure", "azure sdk"] + +dependencies = [ + "isodate>=0.6.1", + "azure-core>=1.37.0", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "parameters.bodyroot._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "parameters", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/header/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/header/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/header/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/header/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/header/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/header/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/header/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/header/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/query/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/query/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/query/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/query/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/query/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/query/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/query/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/parameters/collectionformat/query/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/pyproject.toml index 39a03ebd23b0..965f3bc022be 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-collection-format/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/parameters/path/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/pyproject.toml index 326bc0490f98..14f26987aac2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-path/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/apiview-properties.json index 8ef9d8803e3f..18e1082a3cf8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/apiview-properties.json +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/apiview-properties.json @@ -2,7 +2,9 @@ "CrossLanguagePackageId": "Parameters.Query", "CrossLanguageDefinitionId": { "parameters.query.operations.ConstantOperations.post": "Parameters.Query.Constant.post", - "parameters.query.aio.operations.ConstantOperations.post": "Parameters.Query.Constant.post" + "parameters.query.aio.operations.ConstantOperations.post": "Parameters.Query.Constant.post", + "parameters.query.operations.SpecialCharOperations.dollar_sign": "Parameters.Query.SpecialChar.dollarSign", + "parameters.query.aio.operations.SpecialCharOperations.dollar_sign": "Parameters.Query.SpecialChar.dollarSign" }, - "CrossLanguageVersion": "e2bfb58d3cc1" + "CrossLanguageVersion": "8e99b5930726" } \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/generated_tests/test_query_special_char_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/generated_tests/test_query_special_char_operations.py new file mode 100644 index 000000000000..25e44627ca4a --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/generated_tests/test_query_special_char_operations.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import QueryClientTestBase, QueryPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestQuerySpecialCharOperations(QueryClientTestBase): + @QueryPreparer() + @recorded_by_proxy + def test_special_char_dollar_sign(self, query_endpoint): + client = self.create_client(endpoint=query_endpoint) + response = client.special_char.dollar_sign( + filter="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/generated_tests/test_query_special_char_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/generated_tests/test_query_special_char_operations_async.py new file mode 100644 index 000000000000..a01fd3582a16 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/generated_tests/test_query_special_char_operations_async.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import QueryPreparer +from testpreparer_async import QueryClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestQuerySpecialCharOperationsAsync(QueryClientTestBaseAsync): + @QueryPreparer() + @recorded_by_proxy_async + async def test_special_char_dollar_sign(self, query_endpoint): + client = self.create_async_client(endpoint=query_endpoint) + response = await client.special_char.dollar_sign( + filter="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_client.py index 566b689dddac..e403e3109cac 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_client.py @@ -16,7 +16,7 @@ from ._configuration import QueryClientConfiguration from ._utils.serialization import Deserializer, Serializer -from .operations import ConstantOperations +from .operations import ConstantOperations, SpecialCharOperations if sys.version_info >= (3, 11): from typing import Self @@ -29,6 +29,8 @@ class QueryClient: # pylint: disable=client-accepts-api-version-keyword :ivar constant: ConstantOperations operations :vartype constant: parameters.query.operations.ConstantOperations + :ivar special_char: SpecialCharOperations operations + :vartype special_char: parameters.query.operations.SpecialCharOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -62,6 +64,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._deserialize = Deserializer() self._serialize.client_side_validation = False self.constant = ConstantOperations(self._client, self._config, self._serialize, self._deserialize) + self.special_char = SpecialCharOperations(self._client, self._config, self._serialize, self._deserialize) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/_client.py index 6508a43f5601..97b689f0c73b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/_client.py @@ -16,7 +16,7 @@ from .._utils.serialization import Deserializer, Serializer from ._configuration import QueryClientConfiguration -from .operations import ConstantOperations +from .operations import ConstantOperations, SpecialCharOperations if sys.version_info >= (3, 11): from typing import Self @@ -29,6 +29,8 @@ class QueryClient: # pylint: disable=client-accepts-api-version-keyword :ivar constant: ConstantOperations operations :vartype constant: parameters.query.aio.operations.ConstantOperations + :ivar special_char: SpecialCharOperations operations + :vartype special_char: parameters.query.aio.operations.SpecialCharOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -62,6 +64,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._deserialize = Deserializer() self._serialize.client_side_validation = False self.constant = ConstantOperations(self._client, self._config, self._serialize, self._deserialize) + self.special_char = SpecialCharOperations(self._client, self._config, self._serialize, self._deserialize) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/__init__.py index 8f5275fd5da2..8651ac7024bd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/__init__.py @@ -13,6 +13,7 @@ from ._patch import * # pylint: disable=unused-wildcard-import from ._operations import ConstantOperations # type: ignore +from ._operations import SpecialCharOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -20,6 +21,7 @@ __all__ = [ "ConstantOperations", + "SpecialCharOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/_operations.py index 8ff087080f73..116e9bd254bd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/_operations.py @@ -22,7 +22,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from ..._utils.serialization import Deserializer, Serializer -from ...operations._operations import build_constant_post_request +from ...operations._operations import build_constant_post_request, build_special_char_dollar_sign_request from .._configuration import QueryClientConfiguration T = TypeVar("T") @@ -91,3 +91,68 @@ async def post(self, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore + + +class SpecialCharOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~parameters.query.aio.QueryClient`'s + :attr:`special_char` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueryClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def dollar_sign(self, *, filter: str, **kwargs: Any) -> None: + """dollar_sign. + + :keyword filter: Required. + :paramtype filter: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_special_char_dollar_sign_request( + filter=filter, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/__init__.py index 8f5275fd5da2..8651ac7024bd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/__init__.py @@ -13,6 +13,7 @@ from ._patch import * # pylint: disable=unused-wildcard-import from ._operations import ConstantOperations # type: ignore +from ._operations import SpecialCharOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -20,6 +21,7 @@ __all__ = [ "ConstantOperations", + "SpecialCharOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/_operations.py index 7bd4633fade2..a7e4fe2db504 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/_operations.py @@ -45,6 +45,18 @@ def build_constant_post_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, **kwargs) +def build_special_char_dollar_sign_request(*, filter: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/parameters/query/special-char/dollar-sign" + + # Construct parameters + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + class ConstantOperations: """ .. warning:: @@ -107,3 +119,68 @@ def post(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-st if cls: return cls(pipeline_response, None, {}) # type: ignore + + +class SpecialCharOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~parameters.query.QueryClient`'s + :attr:`special_char` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueryClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def dollar_sign(self, *, filter: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """dollar_sign. + + :keyword filter: Required. + :paramtype filter: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_special_char_dollar_sign_request( + filter=filter, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/parameters/query/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/pyproject.toml index 7195a5207f7b..ea240780a0c4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-query/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/operations/_operations.py index 48cf67e8dff6..e104d992eace 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/operations/_operations.py @@ -25,7 +25,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -81,12 +81,12 @@ async def spread_as_request_body(self, *, name: str, content_type: str = "applic @overload async def spread_as_request_body( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.BodyParameter, *, content_type: str = "application/json", **kwargs: Any ) -> None: """spread_as_request_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.BodyParameter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -113,12 +113,12 @@ async def spread_as_request_body( @distributed_trace_async async def spread_as_request_body( - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, body: Union[JSON, _types.BodyParameter, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any ) -> None: """spread_as_request_body. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BodyParameter, IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.BodyParameter or IO[bytes] :keyword name: Required. :paramtype name: str :return: None @@ -194,12 +194,12 @@ async def spread_composite_request_only_with_body( @overload async def spread_composite_request_only_with_body( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.BodyParameter, *, content_type: str = "application/json", **kwargs: Any ) -> None: """spread_composite_request_only_with_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.BodyParameter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -226,12 +226,13 @@ async def spread_composite_request_only_with_body( @distributed_trace_async async def spread_composite_request_only_with_body( - self, body: Union[_models.BodyParameter, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BodyParameter, _types.BodyParameter, IO[bytes]], **kwargs: Any ) -> None: """spread_composite_request_only_with_body. - :param body: Is one of the following types: BodyParameter, JSON, IO[bytes] Required. - :type body: ~parameters.spread.models.BodyParameter or JSON or IO[bytes] + :param body: Is either a BodyParameter type or a IO[bytes] type. Required. + :type body: ~parameters.spread.models.BodyParameter or ~parameters.spread.types.BodyParameter + or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -360,14 +361,20 @@ async def spread_composite_request( @overload async def spread_composite_request( - self, name: str, body: JSON, *, test_header: str, content_type: str = "application/json", **kwargs: Any + self, + name: str, + body: _types.BodyParameter, + *, + test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_composite_request. :param name: Required. :type name: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.BodyParameter :keyword test_header: Required. :paramtype test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -400,14 +407,20 @@ async def spread_composite_request( @distributed_trace_async async def spread_composite_request( - self, name: str, body: Union[_models.BodyParameter, JSON, IO[bytes]], *, test_header: str, **kwargs: Any + self, + name: str, + body: Union[_models.BodyParameter, _types.BodyParameter, IO[bytes]], + *, + test_header: str, + **kwargs: Any ) -> None: """spread_composite_request. :param name: Required. :type name: str - :param body: Is one of the following types: BodyParameter, JSON, IO[bytes] Required. - :type body: ~parameters.spread.models.BodyParameter or JSON or IO[bytes] + :param body: Is either a BodyParameter type or a IO[bytes] type. Required. + :type body: ~parameters.spread.models.BodyParameter or ~parameters.spread.types.BodyParameter + or IO[bytes] :keyword test_header: Required. :paramtype test_header: str :return: None @@ -484,14 +497,20 @@ async def spread_composite_request_mix( @overload async def spread_composite_request_mix( - self, name: str, body: JSON, *, test_header: str, content_type: str = "application/json", **kwargs: Any + self, + name: str, + body: _types.SpreadCompositeRequestMixRequest, + *, + test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_composite_request_mix. :param name: Required. :type name: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadCompositeRequestMixRequest :keyword test_header: Required. :paramtype test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -524,14 +543,21 @@ async def spread_composite_request_mix( @distributed_trace_async async def spread_composite_request_mix( - self, name: str, body: Union[JSON, IO[bytes]] = _Unset, *, test_header: str, prop: str = _Unset, **kwargs: Any + self, + name: str, + body: Union[JSON, _types.SpreadCompositeRequestMixRequest, IO[bytes]] = _Unset, + *, + test_header: str, + prop: str = _Unset, + **kwargs: Any ) -> None: """spread_composite_request_mix. :param name: Required. :type name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadCompositeRequestMixRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.types.SpreadCompositeRequestMixRequest or IO[bytes] :keyword test_header: Required. :paramtype test_header: str :keyword prop: Required. @@ -627,12 +653,12 @@ async def spread_as_request_body(self, *, name: str, content_type: str = "applic @overload async def spread_as_request_body( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.SpreadAsRequestBodyRequest, *, content_type: str = "application/json", **kwargs: Any ) -> None: """spread_as_request_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadAsRequestBodyRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -659,12 +685,17 @@ async def spread_as_request_body( @distributed_trace_async async def spread_as_request_body( - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SpreadAsRequestBodyRequest, IO[bytes]] = _Unset, + *, + name: str = _Unset, + **kwargs: Any ) -> None: """spread_as_request_body. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadAsRequestBodyRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.types.SpreadAsRequestBodyRequest or IO[bytes] :keyword name: Required. :paramtype name: str :return: None @@ -744,14 +775,20 @@ async def spread_parameter_with_inner_model( @overload async def spread_parameter_with_inner_model( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types.SpreadParameterWithInnerModelRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_parameter_with_inner_model. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadParameterWithInnerModelRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -786,7 +823,7 @@ async def spread_parameter_with_inner_model( async def spread_parameter_with_inner_model( self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SpreadParameterWithInnerModelRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -796,8 +833,9 @@ async def spread_parameter_with_inner_model( :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadParameterWithInnerModelRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadParameterWithInnerModelRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: Required. @@ -881,14 +919,20 @@ async def spread_as_request_parameter( @overload async def spread_as_request_parameter( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types.SpreadAsRequestParameterRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_as_request_parameter. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadAsRequestParameterRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -923,7 +967,7 @@ async def spread_as_request_parameter( async def spread_as_request_parameter( self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SpreadAsRequestParameterRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -933,8 +977,9 @@ async def spread_as_request_parameter( :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadAsRequestParameterRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.types.SpreadAsRequestParameterRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: Required. @@ -1033,14 +1078,20 @@ async def spread_with_multiple_parameters( @overload async def spread_with_multiple_parameters( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types.SpreadWithMultipleParametersRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_with_multiple_parameters. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadWithMultipleParametersRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -1075,7 +1126,7 @@ async def spread_with_multiple_parameters( async def spread_with_multiple_parameters( self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SpreadWithMultipleParametersRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, required_string: str = _Unset, @@ -1088,8 +1139,9 @@ async def spread_with_multiple_parameters( :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadWithMultipleParametersRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadWithMultipleParametersRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword required_string: required string. Required. @@ -1195,14 +1247,20 @@ async def spread_parameter_with_inner_alias( @overload async def spread_parameter_with_inner_alias( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types.SpreadParameterWithInnerAliasRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread an alias with contains another alias property as body. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadParameterWithInnerAliasRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -1237,7 +1295,7 @@ async def spread_parameter_with_inner_alias( async def spread_parameter_with_inner_alias( self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SpreadParameterWithInnerAliasRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -1248,8 +1306,9 @@ async def spread_parameter_with_inner_alias( :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadParameterWithInnerAliasRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadParameterWithInnerAliasRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: name of the Thing. Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/operations/_operations.py index 5ab07b343606..9b21c38f9aad 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/operations/_operations.py @@ -25,7 +25,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import SpreadClientConfiguration from .._utils.model_base import SdkJSONEncoder from .._utils.serialization import Deserializer, Serializer @@ -266,11 +266,13 @@ def spread_as_request_body(self, *, name: str, content_type: str = "application/ """ @overload - def spread_as_request_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def spread_as_request_body( + self, body: _types.BodyParameter, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """spread_as_request_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.BodyParameter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -295,12 +297,12 @@ def spread_as_request_body(self, body: IO[bytes], *, content_type: str = "applic @distributed_trace def spread_as_request_body( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, body: Union[JSON, _types.BodyParameter, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any ) -> None: """spread_as_request_body. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BodyParameter, IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.BodyParameter or IO[bytes] :keyword name: Required. :paramtype name: str :return: None @@ -376,12 +378,12 @@ def spread_composite_request_only_with_body( @overload def spread_composite_request_only_with_body( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.BodyParameter, *, content_type: str = "application/json", **kwargs: Any ) -> None: """spread_composite_request_only_with_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.BodyParameter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -408,12 +410,13 @@ def spread_composite_request_only_with_body( @distributed_trace def spread_composite_request_only_with_body( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BodyParameter, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BodyParameter, _types.BodyParameter, IO[bytes]], **kwargs: Any ) -> None: """spread_composite_request_only_with_body. - :param body: Is one of the following types: BodyParameter, JSON, IO[bytes] Required. - :type body: ~parameters.spread.models.BodyParameter or JSON or IO[bytes] + :param body: Is either a BodyParameter type or a IO[bytes] type. Required. + :type body: ~parameters.spread.models.BodyParameter or ~parameters.spread.types.BodyParameter + or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -544,14 +547,20 @@ def spread_composite_request( @overload def spread_composite_request( - self, name: str, body: JSON, *, test_header: str, content_type: str = "application/json", **kwargs: Any + self, + name: str, + body: _types.BodyParameter, + *, + test_header: str, + content_type: str = "application/json", + **kwargs: Any, ) -> None: """spread_composite_request. :param name: Required. :type name: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.BodyParameter :keyword test_header: Required. :paramtype test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -584,14 +593,20 @@ def spread_composite_request( @distributed_trace def spread_composite_request( # pylint: disable=inconsistent-return-statements - self, name: str, body: Union[_models.BodyParameter, JSON, IO[bytes]], *, test_header: str, **kwargs: Any + self, + name: str, + body: Union[_models.BodyParameter, _types.BodyParameter, IO[bytes]], + *, + test_header: str, + **kwargs: Any, ) -> None: """spread_composite_request. :param name: Required. :type name: str - :param body: Is one of the following types: BodyParameter, JSON, IO[bytes] Required. - :type body: ~parameters.spread.models.BodyParameter or JSON or IO[bytes] + :param body: Is either a BodyParameter type or a IO[bytes] type. Required. + :type body: ~parameters.spread.models.BodyParameter or ~parameters.spread.types.BodyParameter + or IO[bytes] :keyword test_header: Required. :paramtype test_header: str :return: None @@ -668,14 +683,20 @@ def spread_composite_request_mix( @overload def spread_composite_request_mix( - self, name: str, body: JSON, *, test_header: str, content_type: str = "application/json", **kwargs: Any + self, + name: str, + body: _types.SpreadCompositeRequestMixRequest, + *, + test_header: str, + content_type: str = "application/json", + **kwargs: Any, ) -> None: """spread_composite_request_mix. :param name: Required. :type name: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadCompositeRequestMixRequest :keyword test_header: Required. :paramtype test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -708,14 +729,21 @@ def spread_composite_request_mix( @distributed_trace def spread_composite_request_mix( # pylint: disable=inconsistent-return-statements - self, name: str, body: Union[JSON, IO[bytes]] = _Unset, *, test_header: str, prop: str = _Unset, **kwargs: Any + self, + name: str, + body: Union[JSON, _types.SpreadCompositeRequestMixRequest, IO[bytes]] = _Unset, + *, + test_header: str, + prop: str = _Unset, + **kwargs: Any, ) -> None: """spread_composite_request_mix. :param name: Required. :type name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadCompositeRequestMixRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.types.SpreadCompositeRequestMixRequest or IO[bytes] :keyword test_header: Required. :paramtype test_header: str :keyword prop: Required. @@ -810,11 +838,13 @@ def spread_as_request_body(self, *, name: str, content_type: str = "application/ """ @overload - def spread_as_request_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def spread_as_request_body( + self, body: _types.SpreadAsRequestBodyRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """spread_as_request_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadAsRequestBodyRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -839,12 +869,17 @@ def spread_as_request_body(self, body: IO[bytes], *, content_type: str = "applic @distributed_trace def spread_as_request_body( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SpreadAsRequestBodyRequest, IO[bytes]] = _Unset, + *, + name: str = _Unset, + **kwargs: Any, ) -> None: """spread_as_request_body. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadAsRequestBodyRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.types.SpreadAsRequestBodyRequest or IO[bytes] :keyword name: Required. :paramtype name: str :return: None @@ -924,14 +959,20 @@ def spread_parameter_with_inner_model( @overload def spread_parameter_with_inner_model( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types.SpreadParameterWithInnerModelRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any, ) -> None: """spread_parameter_with_inner_model. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadParameterWithInnerModelRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -966,7 +1007,7 @@ def spread_parameter_with_inner_model( def spread_parameter_with_inner_model( # pylint: disable=inconsistent-return-statements self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SpreadParameterWithInnerModelRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -976,8 +1017,9 @@ def spread_parameter_with_inner_model( # pylint: disable=inconsistent-return-st :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadParameterWithInnerModelRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadParameterWithInnerModelRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: Required. @@ -1061,14 +1103,20 @@ def spread_as_request_parameter( @overload def spread_as_request_parameter( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types.SpreadAsRequestParameterRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any, ) -> None: """spread_as_request_parameter. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadAsRequestParameterRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -1103,7 +1151,7 @@ def spread_as_request_parameter( def spread_as_request_parameter( # pylint: disable=inconsistent-return-statements self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SpreadAsRequestParameterRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -1113,8 +1161,9 @@ def spread_as_request_parameter( # pylint: disable=inconsistent-return-statemen :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadAsRequestParameterRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.types.SpreadAsRequestParameterRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: Required. @@ -1213,14 +1262,20 @@ def spread_with_multiple_parameters( @overload def spread_with_multiple_parameters( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types.SpreadWithMultipleParametersRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any, ) -> None: """spread_with_multiple_parameters. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadWithMultipleParametersRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -1255,7 +1310,7 @@ def spread_with_multiple_parameters( def spread_with_multiple_parameters( # pylint: disable=inconsistent-return-statements self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SpreadWithMultipleParametersRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, required_string: str = _Unset, @@ -1268,8 +1323,9 @@ def spread_with_multiple_parameters( # pylint: disable=inconsistent-return-stat :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadWithMultipleParametersRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadWithMultipleParametersRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword required_string: required string. Required. @@ -1375,14 +1431,20 @@ def spread_parameter_with_inner_alias( @overload def spread_parameter_with_inner_alias( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types.SpreadParameterWithInnerAliasRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any, ) -> None: """spread an alias with contains another alias property as body. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadParameterWithInnerAliasRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -1417,7 +1479,7 @@ def spread_parameter_with_inner_alias( def spread_parameter_with_inner_alias( # pylint: disable=inconsistent-return-statements self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SpreadParameterWithInnerAliasRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -1428,8 +1490,9 @@ def spread_parameter_with_inner_alias( # pylint: disable=inconsistent-return-st :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadParameterWithInnerAliasRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadParameterWithInnerAliasRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: name of the Thing. Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/types.py index c9d94550c49e..57fa4f7c4990 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/parameters/spread/types.py @@ -18,3 +18,85 @@ class BodyParameter(TypedDict, total=False): name: Required[str] """Required.""" + + +class SpreadCompositeRequestMixRequest(TypedDict, total=False): + """SpreadCompositeRequestMixRequest. + + :ivar prop: Required. + :vartype prop: str + """ + + prop: Required[str] + """Required.""" + + +class SpreadAsRequestBodyRequest(TypedDict, total=False): + """SpreadAsRequestBodyRequest. + + :ivar name: Required. + :vartype name: str + """ + + name: Required[str] + """Required.""" + + +class SpreadParameterWithInnerModelRequest(TypedDict, total=False): + """SpreadParameterWithInnerModelRequest. + + :ivar name: Required. + :vartype name: str + """ + + name: Required[str] + """Required.""" + + +class SpreadAsRequestParameterRequest(TypedDict, total=False): + """SpreadAsRequestParameterRequest. + + :ivar name: Required. + :vartype name: str + """ + + name: Required[str] + """Required.""" + + +class SpreadWithMultipleParametersRequest(TypedDict, total=False): + """SpreadWithMultipleParametersRequest. + + :ivar required_string: required string. Required. + :vartype required_string: str + :ivar optional_int: optional int. + :vartype optional_int: int + :ivar required_int_list: required int. Required. + :vartype required_int_list: list[int] + :ivar optional_string_list: optional string. + :vartype optional_string_list: list[str] + """ + + requiredString: Required[str] + """required string. Required.""" + optionalInt: int + """optional int.""" + requiredIntList: Required[list[int]] + """required int. Required.""" + optionalStringList: list[str] + """optional string.""" + + +class SpreadParameterWithInnerAliasRequest(TypedDict, total=False): + """SpreadParameterWithInnerAliasRequest. + + :ivar name: name of the Thing. Required. + :vartype name: str + :ivar age: age of the Thing. Required. + :vartype age: int + """ + + name: Required[str] + """name of the Thing. Required.""" + age: Required[int] + """age of the Thing. Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/pyproject.toml index 5d2df804a2f7..9b12bb9ea542 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/parameters-spread/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/types.py deleted file mode 100644 index b23dc7994949..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/payload/contentnegotiation/types.py +++ /dev/null @@ -1,20 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing_extensions import Required, TypedDict - - -class PngImageAsJson(TypedDict, total=False): - """PngImageAsJson. - - :ivar content: Required. - :vartype content: bytes - """ - - content: Required[bytes] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/pyproject.toml index c14da5e477ed..b8703eec447d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-content-negotiation/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/payload/head/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/pyproject.toml index 94537721af29..abaa4876ab47 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-head/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_operations/_operations.py index 01b2fec41965..bd70787fa74a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import JsonMergePatchClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -114,11 +113,13 @@ def create_resource( """ @overload - def create_resource(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Resource: + def create_resource( + self, body: _types.Resource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. :param body: Required. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.Resource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -144,11 +145,14 @@ def create_resource( """ @distributed_trace - def create_resource(self, body: Union[_models.Resource, JSON, IO[bytes]], **kwargs: Any) -> _models.Resource: + def create_resource( + self, body: Union[_models.Resource, _types.Resource, IO[bytes]], **kwargs: Any + ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. - :param body: Is one of the following types: Resource, JSON, IO[bytes] Required. - :type body: ~payload.jsonmergepatch.models.Resource or JSON or IO[bytes] + :param body: Is either a Resource type or a IO[bytes] type. Required. + :type body: ~payload.jsonmergepatch.models.Resource or ~payload.jsonmergepatch.types.Resource + or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~azure.core.exceptions.HttpResponseError: @@ -230,12 +234,12 @@ def update_resource( @overload def update_resource( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.ResourcePatch, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. :param body: Required. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.ResourcePatch :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -261,11 +265,14 @@ def update_resource( """ @distributed_trace - def update_resource(self, body: Union[_models.ResourcePatch, JSON, IO[bytes]], **kwargs: Any) -> _models.Resource: + def update_resource( + self, body: Union[_models.ResourcePatch, _types.ResourcePatch, IO[bytes]], **kwargs: Any + ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. - :param body: Is one of the following types: ResourcePatch, JSON, IO[bytes] Required. - :type body: ~payload.jsonmergepatch.models.ResourcePatch or JSON or IO[bytes] + :param body: Is either a ResourcePatch type or a IO[bytes] type. Required. + :type body: ~payload.jsonmergepatch.models.ResourcePatch or + ~payload.jsonmergepatch.types.ResourcePatch or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~azure.core.exceptions.HttpResponseError: @@ -351,12 +358,16 @@ def update_optional_resource( @overload def update_optional_resource( - self, body: Optional[JSON] = None, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: Optional[_types.ResourcePatch] = None, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any, ) -> _models.Resource: """Test content-type: application/merge-patch+json with optional body. :param body: Default value is None. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.ResourcePatch :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -383,13 +394,13 @@ def update_optional_resource( @distributed_trace def update_optional_resource( - self, body: Optional[Union[_models.ResourcePatch, JSON, IO[bytes]]] = None, **kwargs: Any + self, body: Optional[Union[_models.ResourcePatch, _types.ResourcePatch, IO[bytes]]] = None, **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with optional body. - :param body: Is one of the following types: ResourcePatch, JSON, IO[bytes] Default value is - None. - :type body: ~payload.jsonmergepatch.models.ResourcePatch or JSON or IO[bytes] + :param body: Is either a ResourcePatch type or a IO[bytes] type. Default value is None. + :type body: ~payload.jsonmergepatch.models.ResourcePatch or + ~payload.jsonmergepatch.types.ResourcePatch or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_operations.py index 43895f357c4a..1be69cbc2137 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_json_merge_patch_create_resource_request, build_json_merge_patch_update_optional_resource_request, @@ -37,7 +37,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import JsonMergePatchClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -64,12 +63,12 @@ async def create_resource( @overload async def create_resource( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Resource, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. :param body: Required. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.Resource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -95,11 +94,14 @@ async def create_resource( """ @distributed_trace_async - async def create_resource(self, body: Union[_models.Resource, JSON, IO[bytes]], **kwargs: Any) -> _models.Resource: + async def create_resource( + self, body: Union[_models.Resource, _types.Resource, IO[bytes]], **kwargs: Any + ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. - :param body: Is one of the following types: Resource, JSON, IO[bytes] Required. - :type body: ~payload.jsonmergepatch.models.Resource or JSON or IO[bytes] + :param body: Is either a Resource type or a IO[bytes] type. Required. + :type body: ~payload.jsonmergepatch.models.Resource or ~payload.jsonmergepatch.types.Resource + or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~azure.core.exceptions.HttpResponseError: @@ -181,12 +183,12 @@ async def update_resource( @overload async def update_resource( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.ResourcePatch, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. :param body: Required. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.ResourcePatch :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -213,12 +215,13 @@ async def update_resource( @distributed_trace_async async def update_resource( - self, body: Union[_models.ResourcePatch, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ResourcePatch, _types.ResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. - :param body: Is one of the following types: ResourcePatch, JSON, IO[bytes] Required. - :type body: ~payload.jsonmergepatch.models.ResourcePatch or JSON or IO[bytes] + :param body: Is either a ResourcePatch type or a IO[bytes] type. Required. + :type body: ~payload.jsonmergepatch.models.ResourcePatch or + ~payload.jsonmergepatch.types.ResourcePatch or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~azure.core.exceptions.HttpResponseError: @@ -304,12 +307,16 @@ async def update_optional_resource( @overload async def update_optional_resource( - self, body: Optional[JSON] = None, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: Optional[_types.ResourcePatch] = None, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with optional body. :param body: Default value is None. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.ResourcePatch :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -336,13 +343,13 @@ async def update_optional_resource( @distributed_trace_async async def update_optional_resource( - self, body: Optional[Union[_models.ResourcePatch, JSON, IO[bytes]]] = None, **kwargs: Any + self, body: Optional[Union[_models.ResourcePatch, _types.ResourcePatch, IO[bytes]]] = None, **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with optional body. - :param body: Is one of the following types: ResourcePatch, JSON, IO[bytes] Default value is - None. - :type body: ~payload.jsonmergepatch.models.ResourcePatch or JSON or IO[bytes] + :param body: Is either a ResourcePatch type or a IO[bytes] type. Default value is None. + :type body: ~payload.jsonmergepatch.models.ResourcePatch or + ~payload.jsonmergepatch.types.ResourcePatch or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/types.py index e123287b24a7..e3cc3d77f54a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/payload/jsonmergepatch/types.py @@ -30,15 +30,15 @@ class Resource(TypedDict, total=False): :ivar description: :vartype description: str :ivar map: - :vartype map: dict[str, ~payload.jsonmergepatch.models.InnerModel] + :vartype map: dict[str, "InnerModel"] :ivar array: - :vartype array: list[~payload.jsonmergepatch.models.InnerModel] + :vartype array: list["InnerModel"] :ivar int_value: :vartype int_value: int :ivar float_value: :vartype float_value: float :ivar inner_model: - :vartype inner_model: ~payload.jsonmergepatch.models.InnerModel + :vartype inner_model: "InnerModel" :ivar int_array: :vartype int_array: list[int] """ @@ -60,15 +60,15 @@ class ResourcePatch(TypedDict, total=False): :ivar description: :vartype description: str :ivar map: - :vartype map: dict[str, ~payload.jsonmergepatch.models.InnerModel] + :vartype map: dict[str, "InnerModel"] :ivar array: - :vartype array: list[~payload.jsonmergepatch.models.InnerModel] + :vartype array: list["InnerModel"] :ivar int_value: :vartype int_value: int :ivar float_value: :vartype float_value: float :ivar inner_model: - :vartype inner_model: ~payload.jsonmergepatch.models.InnerModel + :vartype inner_model: "InnerModel" :ivar int_array: :vartype int_array: list[int] """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/pyproject.toml index b849a41724d4..3cf377db03f1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-json-merge-patch/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/stringbody/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/stringbody/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/stringbody/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/stringbody/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/stringbody/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/stringbody/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/stringbody/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/payload/mediatype/stringbody/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/pyproject.toml index 269f8a2c9629..e5fd0ad11692 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-media-type/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/operations/_operations.py index 5e787d82e116..791682c1bb74 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/operations/_operations.py @@ -22,7 +22,7 @@ from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import Model as _Model from ..._utils.serialization import Deserializer, Serializer from ..._utils.utils import prepare_multipart_form_data @@ -47,7 +47,6 @@ ) from .._configuration import MultiPartClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -84,22 +83,23 @@ async def basic(self, body: _models.MultiPartRequest, **kwargs: Any) -> None: """ @overload - async def basic(self, body: JSON, **kwargs: Any) -> None: + async def basic(self, body: _types.MultiPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def basic(self, body: Union[_models.MultiPartRequest, JSON], **kwargs: Any) -> None: + async def basic(self, body: Union[_models.MultiPartRequest, _types.MultiPartRequest], **kwargs: Any) -> None: """Test content-type: multipart/form-data. - :param body: Is either a MultiPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequest or JSON + :param body: Is one of the following types: MultiPartRequest Required. + :type body: ~payload.multipart.models.MultiPartRequest or + ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -158,22 +158,25 @@ async def with_wire_name(self, body: _models.MultiPartRequestWithWireName, **kwa """ @overload - async def with_wire_name(self, body: JSON, **kwargs: Any) -> None: + async def with_wire_name(self, body: _types.MultiPartRequestWithWireName, **kwargs: Any) -> None: """Test content-type: multipart/form-data with wire names. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequestWithWireName :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def with_wire_name(self, body: Union[_models.MultiPartRequestWithWireName, JSON], **kwargs: Any) -> None: + async def with_wire_name( + self, body: Union[_models.MultiPartRequestWithWireName, _types.MultiPartRequestWithWireName], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data with wire names. - :param body: Is either a MultiPartRequestWithWireName type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequestWithWireName or JSON + :param body: Is one of the following types: MultiPartRequestWithWireName Required. + :type body: ~payload.multipart.models.MultiPartRequestWithWireName or + ~payload.multipart.types.MultiPartRequestWithWireName :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -232,22 +235,25 @@ async def optional_parts(self, body: _models.MultiPartOptionalRequest, **kwargs: """ @overload - async def optional_parts(self, body: JSON, **kwargs: Any) -> None: + async def optional_parts(self, body: _types.MultiPartOptionalRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data with optional parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartOptionalRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def optional_parts(self, body: Union[_models.MultiPartOptionalRequest, JSON], **kwargs: Any) -> None: + async def optional_parts( + self, body: Union[_models.MultiPartOptionalRequest, _types.MultiPartOptionalRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data with optional parts. - :param body: Is either a MultiPartOptionalRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartOptionalRequest or JSON + :param body: Is one of the following types: MultiPartOptionalRequest Required. + :type body: ~payload.multipart.models.MultiPartOptionalRequest or + ~payload.multipart.types.MultiPartOptionalRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -306,22 +312,25 @@ async def file_array_and_basic(self, body: _models.ComplexPartsRequest, **kwargs """ @overload - async def file_array_and_basic(self, body: JSON, **kwargs: Any) -> None: + async def file_array_and_basic(self, body: _types.ComplexPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for mixed scenarios. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.ComplexPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def file_array_and_basic(self, body: Union[_models.ComplexPartsRequest, JSON], **kwargs: Any) -> None: + async def file_array_and_basic( + self, body: Union[_models.ComplexPartsRequest, _types.ComplexPartsRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data for mixed scenarios. - :param body: Is either a ComplexPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.ComplexPartsRequest or JSON + :param body: Is one of the following types: ComplexPartsRequest Required. + :type body: ~payload.multipart.models.ComplexPartsRequest or + ~payload.multipart.types.ComplexPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -380,22 +389,23 @@ async def json_part(self, body: _models.JsonPartRequest, **kwargs: Any) -> None: """ @overload - async def json_part(self, body: JSON, **kwargs: Any) -> None: + async def json_part(self, body: _types.JsonPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains json part and binary part. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.JsonPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def json_part(self, body: Union[_models.JsonPartRequest, JSON], **kwargs: Any) -> None: + async def json_part(self, body: Union[_models.JsonPartRequest, _types.JsonPartRequest], **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains json part and binary part. - :param body: Is either a JsonPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.JsonPartRequest or JSON + :param body: Is one of the following types: JsonPartRequest Required. + :type body: ~payload.multipart.models.JsonPartRequest or + ~payload.multipart.types.JsonPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -454,22 +464,25 @@ async def binary_array_parts(self, body: _models.BinaryArrayPartsRequest, **kwar """ @overload - async def binary_array_parts(self, body: JSON, **kwargs: Any) -> None: + async def binary_array_parts(self, body: _types.BinaryArrayPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.BinaryArrayPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def binary_array_parts(self, body: Union[_models.BinaryArrayPartsRequest, JSON], **kwargs: Any) -> None: + async def binary_array_parts( + self, body: Union[_models.BinaryArrayPartsRequest, _types.BinaryArrayPartsRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. - :param body: Is either a BinaryArrayPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.BinaryArrayPartsRequest or JSON + :param body: Is one of the following types: BinaryArrayPartsRequest Required. + :type body: ~payload.multipart.models.BinaryArrayPartsRequest or + ~payload.multipart.types.BinaryArrayPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -528,22 +541,25 @@ async def multi_binary_parts(self, body: _models.MultiBinaryPartsRequest, **kwar """ @overload - async def multi_binary_parts(self, body: JSON, **kwargs: Any) -> None: + async def multi_binary_parts(self, body: _types.MultiBinaryPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiBinaryPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def multi_binary_parts(self, body: Union[_models.MultiBinaryPartsRequest, JSON], **kwargs: Any) -> None: + async def multi_binary_parts( + self, body: Union[_models.MultiBinaryPartsRequest, _types.MultiBinaryPartsRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. - :param body: Is either a MultiBinaryPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiBinaryPartsRequest or JSON + :param body: Is one of the following types: MultiBinaryPartsRequest Required. + :type body: ~payload.multipart.models.MultiBinaryPartsRequest or + ~payload.multipart.types.MultiBinaryPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -602,11 +618,11 @@ async def check_file_name_and_content_type(self, body: _models.MultiPartRequest, """ @overload - async def check_file_name_and_content_type(self, body: JSON, **kwargs: Any) -> None: + async def check_file_name_and_content_type(self, body: _types.MultiPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -614,12 +630,13 @@ async def check_file_name_and_content_type(self, body: JSON, **kwargs: Any) -> N @distributed_trace_async async def check_file_name_and_content_type( - self, body: Union[_models.MultiPartRequest, JSON], **kwargs: Any + self, body: Union[_models.MultiPartRequest, _types.MultiPartRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a MultiPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequest or JSON + :param body: Is one of the following types: MultiPartRequest Required. + :type body: ~payload.multipart.models.MultiPartRequest or + ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -678,22 +695,25 @@ async def anonymous_model(self, body: _models.AnonymousModelRequest, **kwargs: A """ @overload - async def anonymous_model(self, body: JSON, **kwargs: Any) -> None: + async def anonymous_model(self, body: _types.AnonymousModelRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.AnonymousModelRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def anonymous_model(self, body: Union[_models.AnonymousModelRequest, JSON], **kwargs: Any) -> None: + async def anonymous_model( + self, body: Union[_models.AnonymousModelRequest, _types.AnonymousModelRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a AnonymousModelRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.AnonymousModelRequest or JSON + :param body: Is one of the following types: AnonymousModelRequest Required. + :type body: ~payload.multipart.models.AnonymousModelRequest or + ~payload.multipart.types.AnonymousModelRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -777,11 +797,11 @@ async def json_array_and_file_array(self, body: _models.ComplexHttpPartsModelReq """ @overload - async def json_array_and_file_array(self, body: JSON, **kwargs: Any) -> None: + async def json_array_and_file_array(self, body: _types.ComplexHttpPartsModelRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for mixed scenarios. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.ComplexHttpPartsModelRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -789,12 +809,13 @@ async def json_array_and_file_array(self, body: JSON, **kwargs: Any) -> None: @distributed_trace_async async def json_array_and_file_array( - self, body: Union[_models.ComplexHttpPartsModelRequest, JSON], **kwargs: Any + self, body: Union[_models.ComplexHttpPartsModelRequest, _types.ComplexHttpPartsModelRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for mixed scenarios. - :param body: Is either a ComplexHttpPartsModelRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.ComplexHttpPartsModelRequest or JSON + :param body: Is one of the following types: ComplexHttpPartsModelRequest Required. + :type body: ~payload.multipart.models.ComplexHttpPartsModelRequest or + ~payload.multipart.types.ComplexHttpPartsModelRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -873,11 +894,13 @@ async def upload_file_specific_content_type( """ @overload - async def upload_file_specific_content_type(self, body: JSON, **kwargs: Any) -> None: + async def upload_file_specific_content_type( + self, body: _types.UploadFileSpecificContentTypeRequest, **kwargs: Any + ) -> None: """upload_file_specific_content_type. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.UploadFileSpecificContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -885,12 +908,15 @@ async def upload_file_specific_content_type(self, body: JSON, **kwargs: Any) -> @distributed_trace_async async def upload_file_specific_content_type( - self, body: Union[_models.UploadFileSpecificContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[_models.UploadFileSpecificContentTypeRequest, _types.UploadFileSpecificContentTypeRequest], + **kwargs: Any ) -> None: """upload_file_specific_content_type. - :param body: Is either a UploadFileSpecificContentTypeRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.UploadFileSpecificContentTypeRequest or JSON + :param body: Is one of the following types: UploadFileSpecificContentTypeRequest Required. + :type body: ~payload.multipart.models.UploadFileSpecificContentTypeRequest or + ~payload.multipart.types.UploadFileSpecificContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -951,11 +977,13 @@ async def upload_file_required_filename( """ @overload - async def upload_file_required_filename(self, body: JSON, **kwargs: Any) -> None: + async def upload_file_required_filename( + self, body: _types.UploadFileRequiredFilenameRequest, **kwargs: Any + ) -> None: """upload_file_required_filename. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.UploadFileRequiredFilenameRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -963,12 +991,15 @@ async def upload_file_required_filename(self, body: JSON, **kwargs: Any) -> None @distributed_trace_async async def upload_file_required_filename( - self, body: Union[_models.UploadFileRequiredFilenameRequest, JSON], **kwargs: Any + self, + body: Union[_models.UploadFileRequiredFilenameRequest, _types.UploadFileRequiredFilenameRequest], + **kwargs: Any ) -> None: """upload_file_required_filename. - :param body: Is either a UploadFileRequiredFilenameRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.UploadFileRequiredFilenameRequest or JSON + :param body: Is one of the following types: UploadFileRequiredFilenameRequest Required. + :type body: ~payload.multipart.models.UploadFileRequiredFilenameRequest or + ~payload.multipart.types.UploadFileRequiredFilenameRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1027,22 +1058,25 @@ async def upload_file_array(self, body: _models.UploadFileArrayRequest, **kwargs """ @overload - async def upload_file_array(self, body: JSON, **kwargs: Any) -> None: + async def upload_file_array(self, body: _types.UploadFileArrayRequest, **kwargs: Any) -> None: """upload_file_array. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.UploadFileArrayRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def upload_file_array(self, body: Union[_models.UploadFileArrayRequest, JSON], **kwargs: Any) -> None: + async def upload_file_array( + self, body: Union[_models.UploadFileArrayRequest, _types.UploadFileArrayRequest], **kwargs: Any + ) -> None: """upload_file_array. - :param body: Is either a UploadFileArrayRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.UploadFileArrayRequest or JSON + :param body: Is one of the following types: UploadFileArrayRequest Required. + :type body: ~payload.multipart.models.UploadFileArrayRequest or + ~payload.multipart.types.UploadFileArrayRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1121,11 +1155,13 @@ async def image_jpeg_content_type( """ @overload - async def image_jpeg_content_type(self, body: JSON, **kwargs: Any) -> None: + async def image_jpeg_content_type( + self, body: _types.FileWithHttpPartSpecificContentTypeRequest, **kwargs: Any + ) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartSpecificContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1133,13 +1169,18 @@ async def image_jpeg_content_type(self, body: JSON, **kwargs: Any) -> None: @distributed_trace_async async def image_jpeg_content_type( - self, body: Union[_models.FileWithHttpPartSpecificContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models.FileWithHttpPartSpecificContentTypeRequest, _types.FileWithHttpPartSpecificContentTypeRequest + ], + **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a FileWithHttpPartSpecificContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartSpecificContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartSpecificContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartSpecificContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartSpecificContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1200,11 +1241,13 @@ async def required_content_type( """ @overload - async def required_content_type(self, body: JSON, **kwargs: Any) -> None: + async def required_content_type( + self, body: _types.FileWithHttpPartRequiredContentTypeRequest, **kwargs: Any + ) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartRequiredContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1212,13 +1255,18 @@ async def required_content_type(self, body: JSON, **kwargs: Any) -> None: @distributed_trace_async async def required_content_type( - self, body: Union[_models.FileWithHttpPartRequiredContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models.FileWithHttpPartRequiredContentTypeRequest, _types.FileWithHttpPartRequiredContentTypeRequest + ], + **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a FileWithHttpPartRequiredContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartRequiredContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartRequiredContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartRequiredContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartRequiredContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1279,11 +1327,13 @@ async def optional_content_type( """ @overload - async def optional_content_type(self, body: JSON, **kwargs: Any) -> None: + async def optional_content_type( + self, body: _types.FileWithHttpPartOptionalContentTypeRequest, **kwargs: Any + ) -> None: """Test content-type: multipart/form-data for optional content type. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartOptionalContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1291,13 +1341,18 @@ async def optional_content_type(self, body: JSON, **kwargs: Any) -> None: @distributed_trace_async async def optional_content_type( - self, body: Union[_models.FileWithHttpPartOptionalContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models.FileWithHttpPartOptionalContentTypeRequest, _types.FileWithHttpPartOptionalContentTypeRequest + ], + **kwargs: Any ) -> None: """Test content-type: multipart/form-data for optional content type. - :param body: Is either a FileWithHttpPartOptionalContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartOptionalContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartOptionalContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartOptionalContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartOptionalContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1374,22 +1429,22 @@ async def float(self, body: _models.FloatRequest, **kwargs: Any) -> None: """ @overload - async def float(self, body: JSON, **kwargs: Any) -> None: + async def float(self, body: _types.FloatRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for non string. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FloatRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def float(self, body: Union[_models.FloatRequest, JSON], **kwargs: Any) -> None: + async def float(self, body: Union[_models.FloatRequest, _types.FloatRequest], **kwargs: Any) -> None: """Test content-type: multipart/form-data for non string. - :param body: Is either a FloatRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.FloatRequest or JSON + :param body: Is one of the following types: FloatRequest Required. + :type body: ~payload.multipart.models.FloatRequest or ~payload.multipart.types.FloatRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/operations/_operations.py index 877227b25b34..417c6e7331a3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/operations/_operations.py @@ -23,13 +23,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import MultiPartClientConfiguration from .._utils.model_base import Model as _Model from .._utils.serialization import Deserializer, Serializer from .._utils.utils import prepare_multipart_form_data -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -236,11 +235,11 @@ def basic(self, body: _models.MultiPartRequest, **kwargs: Any) -> None: """ @overload - def basic(self, body: JSON, **kwargs: Any) -> None: + def basic(self, body: _types.MultiPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -248,12 +247,13 @@ def basic(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def basic( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.MultiPartRequest, JSON], **kwargs: Any + self, body: Union[_models.MultiPartRequest, _types.MultiPartRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a MultiPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequest or JSON + :param body: Is one of the following types: MultiPartRequest Required. + :type body: ~payload.multipart.models.MultiPartRequest or + ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -312,11 +312,11 @@ def with_wire_name(self, body: _models.MultiPartRequestWithWireName, **kwargs: A """ @overload - def with_wire_name(self, body: JSON, **kwargs: Any) -> None: + def with_wire_name(self, body: _types.MultiPartRequestWithWireName, **kwargs: Any) -> None: """Test content-type: multipart/form-data with wire names. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequestWithWireName :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -324,12 +324,13 @@ def with_wire_name(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def with_wire_name( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.MultiPartRequestWithWireName, JSON], **kwargs: Any + self, body: Union[_models.MultiPartRequestWithWireName, _types.MultiPartRequestWithWireName], **kwargs: Any ) -> None: """Test content-type: multipart/form-data with wire names. - :param body: Is either a MultiPartRequestWithWireName type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequestWithWireName or JSON + :param body: Is one of the following types: MultiPartRequestWithWireName Required. + :type body: ~payload.multipart.models.MultiPartRequestWithWireName or + ~payload.multipart.types.MultiPartRequestWithWireName :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -388,11 +389,11 @@ def optional_parts(self, body: _models.MultiPartOptionalRequest, **kwargs: Any) """ @overload - def optional_parts(self, body: JSON, **kwargs: Any) -> None: + def optional_parts(self, body: _types.MultiPartOptionalRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data with optional parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartOptionalRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -400,12 +401,13 @@ def optional_parts(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def optional_parts( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.MultiPartOptionalRequest, JSON], **kwargs: Any + self, body: Union[_models.MultiPartOptionalRequest, _types.MultiPartOptionalRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data with optional parts. - :param body: Is either a MultiPartOptionalRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartOptionalRequest or JSON + :param body: Is one of the following types: MultiPartOptionalRequest Required. + :type body: ~payload.multipart.models.MultiPartOptionalRequest or + ~payload.multipart.types.MultiPartOptionalRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -464,11 +466,11 @@ def file_array_and_basic(self, body: _models.ComplexPartsRequest, **kwargs: Any) """ @overload - def file_array_and_basic(self, body: JSON, **kwargs: Any) -> None: + def file_array_and_basic(self, body: _types.ComplexPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for mixed scenarios. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.ComplexPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -476,12 +478,13 @@ def file_array_and_basic(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def file_array_and_basic( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ComplexPartsRequest, JSON], **kwargs: Any + self, body: Union[_models.ComplexPartsRequest, _types.ComplexPartsRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for mixed scenarios. - :param body: Is either a ComplexPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.ComplexPartsRequest or JSON + :param body: Is one of the following types: ComplexPartsRequest Required. + :type body: ~payload.multipart.models.ComplexPartsRequest or + ~payload.multipart.types.ComplexPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -540,11 +543,11 @@ def json_part(self, body: _models.JsonPartRequest, **kwargs: Any) -> None: """ @overload - def json_part(self, body: JSON, **kwargs: Any) -> None: + def json_part(self, body: _types.JsonPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains json part and binary part. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.JsonPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -552,12 +555,13 @@ def json_part(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def json_part( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.JsonPartRequest, JSON], **kwargs: Any + self, body: Union[_models.JsonPartRequest, _types.JsonPartRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for scenario contains json part and binary part. - :param body: Is either a JsonPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.JsonPartRequest or JSON + :param body: Is one of the following types: JsonPartRequest Required. + :type body: ~payload.multipart.models.JsonPartRequest or + ~payload.multipart.types.JsonPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -616,11 +620,11 @@ def binary_array_parts(self, body: _models.BinaryArrayPartsRequest, **kwargs: An """ @overload - def binary_array_parts(self, body: JSON, **kwargs: Any) -> None: + def binary_array_parts(self, body: _types.BinaryArrayPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.BinaryArrayPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -628,12 +632,13 @@ def binary_array_parts(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def binary_array_parts( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BinaryArrayPartsRequest, JSON], **kwargs: Any + self, body: Union[_models.BinaryArrayPartsRequest, _types.BinaryArrayPartsRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. - :param body: Is either a BinaryArrayPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.BinaryArrayPartsRequest or JSON + :param body: Is one of the following types: BinaryArrayPartsRequest Required. + :type body: ~payload.multipart.models.BinaryArrayPartsRequest or + ~payload.multipart.types.BinaryArrayPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -692,11 +697,11 @@ def multi_binary_parts(self, body: _models.MultiBinaryPartsRequest, **kwargs: An """ @overload - def multi_binary_parts(self, body: JSON, **kwargs: Any) -> None: + def multi_binary_parts(self, body: _types.MultiBinaryPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiBinaryPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -704,12 +709,13 @@ def multi_binary_parts(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def multi_binary_parts( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.MultiBinaryPartsRequest, JSON], **kwargs: Any + self, body: Union[_models.MultiBinaryPartsRequest, _types.MultiBinaryPartsRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. - :param body: Is either a MultiBinaryPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiBinaryPartsRequest or JSON + :param body: Is one of the following types: MultiBinaryPartsRequest Required. + :type body: ~payload.multipart.models.MultiBinaryPartsRequest or + ~payload.multipart.types.MultiBinaryPartsRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -768,11 +774,11 @@ def check_file_name_and_content_type(self, body: _models.MultiPartRequest, **kwa """ @overload - def check_file_name_and_content_type(self, body: JSON, **kwargs: Any) -> None: + def check_file_name_and_content_type(self, body: _types.MultiPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -780,12 +786,13 @@ def check_file_name_and_content_type(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def check_file_name_and_content_type( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.MultiPartRequest, JSON], **kwargs: Any + self, body: Union[_models.MultiPartRequest, _types.MultiPartRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a MultiPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequest or JSON + :param body: Is one of the following types: MultiPartRequest Required. + :type body: ~payload.multipart.models.MultiPartRequest or + ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -844,11 +851,11 @@ def anonymous_model(self, body: _models.AnonymousModelRequest, **kwargs: Any) -> """ @overload - def anonymous_model(self, body: JSON, **kwargs: Any) -> None: + def anonymous_model(self, body: _types.AnonymousModelRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.AnonymousModelRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -856,12 +863,13 @@ def anonymous_model(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def anonymous_model( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.AnonymousModelRequest, JSON], **kwargs: Any + self, body: Union[_models.AnonymousModelRequest, _types.AnonymousModelRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a AnonymousModelRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.AnonymousModelRequest or JSON + :param body: Is one of the following types: AnonymousModelRequest Required. + :type body: ~payload.multipart.models.AnonymousModelRequest or + ~payload.multipart.types.AnonymousModelRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -945,11 +953,11 @@ def json_array_and_file_array(self, body: _models.ComplexHttpPartsModelRequest, """ @overload - def json_array_and_file_array(self, body: JSON, **kwargs: Any) -> None: + def json_array_and_file_array(self, body: _types.ComplexHttpPartsModelRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for mixed scenarios. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.ComplexHttpPartsModelRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -957,12 +965,13 @@ def json_array_and_file_array(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def json_array_and_file_array( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ComplexHttpPartsModelRequest, JSON], **kwargs: Any + self, body: Union[_models.ComplexHttpPartsModelRequest, _types.ComplexHttpPartsModelRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for mixed scenarios. - :param body: Is either a ComplexHttpPartsModelRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.ComplexHttpPartsModelRequest or JSON + :param body: Is one of the following types: ComplexHttpPartsModelRequest Required. + :type body: ~payload.multipart.models.ComplexHttpPartsModelRequest or + ~payload.multipart.types.ComplexHttpPartsModelRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1041,11 +1050,13 @@ def upload_file_specific_content_type( """ @overload - def upload_file_specific_content_type(self, body: JSON, **kwargs: Any) -> None: + def upload_file_specific_content_type( + self, body: _types.UploadFileSpecificContentTypeRequest, **kwargs: Any + ) -> None: """upload_file_specific_content_type. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.UploadFileSpecificContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1053,12 +1064,15 @@ def upload_file_specific_content_type(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def upload_file_specific_content_type( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UploadFileSpecificContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[_models.UploadFileSpecificContentTypeRequest, _types.UploadFileSpecificContentTypeRequest], + **kwargs: Any, ) -> None: """upload_file_specific_content_type. - :param body: Is either a UploadFileSpecificContentTypeRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.UploadFileSpecificContentTypeRequest or JSON + :param body: Is one of the following types: UploadFileSpecificContentTypeRequest Required. + :type body: ~payload.multipart.models.UploadFileSpecificContentTypeRequest or + ~payload.multipart.types.UploadFileSpecificContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1117,11 +1131,11 @@ def upload_file_required_filename(self, body: _models.UploadFileRequiredFilename """ @overload - def upload_file_required_filename(self, body: JSON, **kwargs: Any) -> None: + def upload_file_required_filename(self, body: _types.UploadFileRequiredFilenameRequest, **kwargs: Any) -> None: """upload_file_required_filename. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.UploadFileRequiredFilenameRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1129,12 +1143,15 @@ def upload_file_required_filename(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def upload_file_required_filename( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UploadFileRequiredFilenameRequest, JSON], **kwargs: Any + self, + body: Union[_models.UploadFileRequiredFilenameRequest, _types.UploadFileRequiredFilenameRequest], + **kwargs: Any, ) -> None: """upload_file_required_filename. - :param body: Is either a UploadFileRequiredFilenameRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.UploadFileRequiredFilenameRequest or JSON + :param body: Is one of the following types: UploadFileRequiredFilenameRequest Required. + :type body: ~payload.multipart.models.UploadFileRequiredFilenameRequest or + ~payload.multipart.types.UploadFileRequiredFilenameRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1193,11 +1210,11 @@ def upload_file_array(self, body: _models.UploadFileArrayRequest, **kwargs: Any) """ @overload - def upload_file_array(self, body: JSON, **kwargs: Any) -> None: + def upload_file_array(self, body: _types.UploadFileArrayRequest, **kwargs: Any) -> None: """upload_file_array. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.UploadFileArrayRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1205,12 +1222,13 @@ def upload_file_array(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def upload_file_array( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UploadFileArrayRequest, JSON], **kwargs: Any + self, body: Union[_models.UploadFileArrayRequest, _types.UploadFileArrayRequest], **kwargs: Any ) -> None: """upload_file_array. - :param body: Is either a UploadFileArrayRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.UploadFileArrayRequest or JSON + :param body: Is one of the following types: UploadFileArrayRequest Required. + :type body: ~payload.multipart.models.UploadFileArrayRequest or + ~payload.multipart.types.UploadFileArrayRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1287,11 +1305,11 @@ def image_jpeg_content_type(self, body: _models.FileWithHttpPartSpecificContentT """ @overload - def image_jpeg_content_type(self, body: JSON, **kwargs: Any) -> None: + def image_jpeg_content_type(self, body: _types.FileWithHttpPartSpecificContentTypeRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartSpecificContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1299,13 +1317,18 @@ def image_jpeg_content_type(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def image_jpeg_content_type( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FileWithHttpPartSpecificContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models.FileWithHttpPartSpecificContentTypeRequest, _types.FileWithHttpPartSpecificContentTypeRequest + ], + **kwargs: Any, ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a FileWithHttpPartSpecificContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartSpecificContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartSpecificContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartSpecificContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartSpecificContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1364,11 +1387,11 @@ def required_content_type(self, body: _models.FileWithHttpPartRequiredContentTyp """ @overload - def required_content_type(self, body: JSON, **kwargs: Any) -> None: + def required_content_type(self, body: _types.FileWithHttpPartRequiredContentTypeRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartRequiredContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1376,13 +1399,18 @@ def required_content_type(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def required_content_type( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FileWithHttpPartRequiredContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models.FileWithHttpPartRequiredContentTypeRequest, _types.FileWithHttpPartRequiredContentTypeRequest + ], + **kwargs: Any, ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a FileWithHttpPartRequiredContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartRequiredContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartRequiredContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartRequiredContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartRequiredContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1441,11 +1469,11 @@ def optional_content_type(self, body: _models.FileWithHttpPartOptionalContentTyp """ @overload - def optional_content_type(self, body: JSON, **kwargs: Any) -> None: + def optional_content_type(self, body: _types.FileWithHttpPartOptionalContentTypeRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for optional content type. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartOptionalContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1453,13 +1481,18 @@ def optional_content_type(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def optional_content_type( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FileWithHttpPartOptionalContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models.FileWithHttpPartOptionalContentTypeRequest, _types.FileWithHttpPartOptionalContentTypeRequest + ], + **kwargs: Any, ) -> None: """Test content-type: multipart/form-data for optional content type. - :param body: Is either a FileWithHttpPartOptionalContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartOptionalContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartOptionalContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartOptionalContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartOptionalContentTypeRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1536,11 +1569,11 @@ def float(self, body: _models.FloatRequest, **kwargs: Any) -> None: """ @overload - def float(self, body: JSON, **kwargs: Any) -> None: + def float(self, body: _types.FloatRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for non string. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FloatRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1548,12 +1581,12 @@ def float(self, body: JSON, **kwargs: Any) -> None: @distributed_trace def float( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FloatRequest, JSON], **kwargs: Any + self, body: Union[_models.FloatRequest, _types.FloatRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for non string. - :param body: Is either a FloatRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.FloatRequest or JSON + :param body: Is one of the following types: FloatRequest Required. + :type body: ~payload.multipart.models.FloatRequest or ~payload.multipart.types.FloatRequest :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/types.py index 93a2de61a67a..03ed6691020b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/payload/multipart/types.py @@ -26,7 +26,7 @@ class AnonymousModelRequest(TypedDict, total=False): """AnonymousModelRequest. :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ profileImage: Required[FileType] @@ -39,7 +39,7 @@ class BinaryArrayPartsRequest(TypedDict, total=False): :ivar id: Required. :vartype id: str :ivar pictures: Required. - :vartype pictures: list[~payload.multipart._utils.utils.FileType] + :vartype pictures: list[FileType] """ id: Required[str] @@ -54,13 +54,13 @@ class ComplexHttpPartsModelRequest(TypedDict, total=False): :ivar id: Required. :vartype id: str :ivar address: Required. - :vartype address: ~payload.multipart.models.Address + :vartype address: "Address" :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType :ivar previous_addresses: Required. - :vartype previous_addresses: list[~payload.multipart.models.Address] + :vartype previous_addresses: list["Address"] :ivar pictures: Required. - :vartype pictures: list[~payload.multipart._utils.utils.FileType] + :vartype pictures: list[FileType] """ id: Required[str] @@ -81,11 +81,11 @@ class ComplexPartsRequest(TypedDict, total=False): :ivar id: Required. :vartype id: str :ivar address: Required. - :vartype address: ~payload.multipart.models.Address + :vartype address: "Address" :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType :ivar pictures: Required. - :vartype pictures: list[~payload.multipart._utils.utils.FileType] + :vartype pictures: list[FileType] """ id: Required[str] @@ -102,7 +102,7 @@ class FileWithHttpPartOptionalContentTypeRequest(TypedDict, total=False): # pyl """FileWithHttpPartOptionalContentTypeRequest. :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ profileImage: Required[FileType] @@ -113,7 +113,7 @@ class FileWithHttpPartRequiredContentTypeRequest(TypedDict, total=False): # pyl """FileWithHttpPartRequiredContentTypeRequest. :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ profileImage: Required[FileType] @@ -124,7 +124,7 @@ class FileWithHttpPartSpecificContentTypeRequest(TypedDict, total=False): # pyl """FileWithHttpPartSpecificContentTypeRequest. :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ profileImage: Required[FileType] @@ -146,9 +146,9 @@ class JsonPartRequest(TypedDict, total=False): """JsonPartRequest. :ivar address: Required. - :vartype address: ~payload.multipart.models.Address + :vartype address: "Address" :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ address: Required["Address"] @@ -161,9 +161,9 @@ class MultiBinaryPartsRequest(TypedDict, total=False): """MultiBinaryPartsRequest. :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType :ivar picture: - :vartype picture: ~payload.multipart._utils.utils.FileType + :vartype picture: FileType """ profileImage: Required[FileType] @@ -177,7 +177,7 @@ class MultiPartOptionalRequest(TypedDict, total=False): :ivar id: :vartype id: str :ivar profile_image: - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ id: str @@ -190,7 +190,7 @@ class MultiPartRequest(TypedDict, total=False): :ivar id: Required. :vartype id: str :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ id: Required[str] @@ -205,7 +205,7 @@ class MultiPartRequestWithWireName(TypedDict, total=False): :ivar identifier: Required. :vartype identifier: str :ivar image: Required. - :vartype image: ~payload.multipart._utils.utils.FileType + :vartype image: FileType """ id: Required[str] @@ -218,7 +218,7 @@ class UploadFileArrayRequest(TypedDict, total=False): """UploadFileArrayRequest. :ivar files: Required. - :vartype files: list[~payload.multipart._utils.utils.FileType] + :vartype files: list[FileType] """ files: Required[list[FileType]] @@ -229,7 +229,7 @@ class UploadFileRequiredFilenameRequest(TypedDict, total=False): """UploadFileRequiredFilenameRequest. :ivar file: Required. - :vartype file: ~payload.multipart._utils.utils.FileType + :vartype file: FileType """ file: Required[FileType] @@ -240,7 +240,7 @@ class UploadFileSpecificContentTypeRequest(TypedDict, total=False): """UploadFileSpecificContentTypeRequest. :ivar file: Required. - :vartype file: ~payload.multipart._utils.utils.FileType + :vartype file: FileType """ file: Required[FileType] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/pyproject.toml index 73f2e368995c..a82031208d71 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-multipart/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_operations/_patch.py deleted file mode 100644 index ea765788358a..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_operations/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/aio/_operations/_patch.py deleted file mode 100644 index ea765788358a..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/aio/_operations/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/pagesize/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/pagesize/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/pagesize/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/pagesize/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/pagesize/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/pagesize/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/pagesize/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/pagesize/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_operations.py index e862bb9ebc9f..8113015dfc58 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_operations.py @@ -25,14 +25,13 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..... import models as _models4 from ....._utils.model_base import SdkJSONEncoder, _deserialize from ....._utils.serialization import Deserializer, Serializer from .....aio._configuration import PageableClientConfiguration from ...operations._operations import build_server_driven_pagination_alternate_initial_verb_post_request -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -72,12 +71,12 @@ def post( @overload def post( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Filter, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncItemPaged["_models4.Pet"]: """post. :param body: Required. - :type body: JSON + :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.types.Filter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -103,12 +102,14 @@ def post( """ @distributed_trace - def post(self, body: Union[_models2.Filter, JSON, IO[bytes]], **kwargs: Any) -> AsyncItemPaged["_models4.Pet"]: + def post( + self, body: Union[_models2.Filter, _types_models2.Filter, IO[bytes]], **kwargs: Any + ) -> AsyncItemPaged["_models4.Pet"]: """post. - :param body: Is one of the following types: Filter, JSON, IO[bytes] Required. - :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.models.Filter or JSON - or IO[bytes] + :param body: Is either a Filter type or a IO[bytes] type. Required. + :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.models.Filter or + ~payload.pageable.serverdrivenpagination.alternateinitialverb.types.Filter or IO[bytes] :return: An iterator like instance of Pet :rtype: ~azure.core.async_paging.AsyncItemPaged[~payload.pageable.models.Pet] :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_operations.py index 2bb6f125c34c..650890ca7ed9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_operations.py @@ -25,13 +25,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from .... import models as _models3 from ...._configuration import PageableClientConfiguration from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -92,11 +91,13 @@ def post( """ @overload - def post(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> ItemPaged["_models3.Pet"]: + def post( + self, body: _types_models1.Filter, *, content_type: str = "application/json", **kwargs: Any + ) -> ItemPaged["_models3.Pet"]: """post. :param body: Required. - :type body: JSON + :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.types.Filter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -122,12 +123,14 @@ def post( """ @distributed_trace - def post(self, body: Union[_models1.Filter, JSON, IO[bytes]], **kwargs: Any) -> ItemPaged["_models3.Pet"]: + def post( + self, body: Union[_models1.Filter, _types_models1.Filter, IO[bytes]], **kwargs: Any + ) -> ItemPaged["_models3.Pet"]: """post. - :param body: Is one of the following types: Filter, JSON, IO[bytes] Required. - :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.models.Filter or JSON - or IO[bytes] + :param body: Is either a Filter type or a IO[bytes] type. Required. + :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.models.Filter or + ~payload.pageable.serverdrivenpagination.alternateinitialverb.types.Filter or IO[bytes] :return: An iterator like instance of Pet :rtype: ~azure.core.paging.ItemPaged[~payload.pageable.models.Pet] :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/types.py deleted file mode 100644 index 0c9782b86d7b..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/types.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import TYPE_CHECKING -from typing_extensions import Required, TypedDict - -if TYPE_CHECKING: - from ...types import Pet - - -class RequestHeaderNestedResponseBodyResponseNestedItems(TypedDict, total=False): # pylint: disable=name-too-long - """RequestHeaderNestedResponseBodyResponseNestedItems. - - :ivar pets: Required. - :vartype pets: list[~payload.pageable.models.Pet] - """ - - pets: Required[list["Pet"]] - """Required.""" - - -class RequestHeaderNestedResponseBodyResponseNestedNext(TypedDict, total=False): # pylint: disable=name-too-long - """RequestHeaderNestedResponseBodyResponseNestedNext. - - :ivar next_token: - :vartype next_token: str - """ - - nextToken: str - - -class RequestQueryNestedResponseBodyResponseNestedItems(TypedDict, total=False): # pylint: disable=name-too-long - """RequestQueryNestedResponseBodyResponseNestedItems. - - :ivar pets: Required. - :vartype pets: list[~payload.pageable.models.Pet] - """ - - pets: Required[list["Pet"]] - """Required.""" - - -class RequestQueryNestedResponseBodyResponseNestedNext(TypedDict, total=False): # pylint: disable=name-too-long - """RequestQueryNestedResponseBodyResponseNestedNext. - - :ivar next_token: - :vartype next_token: str - """ - - nextToken: str diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/serverdrivenpagination/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/types.py deleted file mode 100644 index 9cf62bff2c7b..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/types.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing_extensions import Required, TypedDict - - -class Pet(TypedDict, total=False): - """Pet. - - :ivar id: Required. - :vartype id: str - :ivar name: Required. - :vartype name: str - """ - - id: Required[str] - """Required.""" - name: Required[str] - """Required.""" - - -class XmlPet(TypedDict, total=False): - """An XML pet item. - - :ivar id: Required. - :vartype id: str - :ivar name: Required. - :vartype name: str - """ - - id: Required[str] - """Required.""" - name: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/xmlpagination/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/xmlpagination/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/xmlpagination/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/xmlpagination/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/xmlpagination/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/xmlpagination/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/xmlpagination/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/payload/pageable/xmlpagination/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/pyproject.toml index f24b501875d8..8f55d1efddbf 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-pageable/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_utils/model_base.py index bd5b9caf1022..1934415c1369 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/types.py deleted file mode 100644 index c871cb999e29..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/payload/xml/types.py +++ /dev/null @@ -1,394 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing import TYPE_CHECKING, Union -from typing_extensions import Required, TypedDict - -if TYPE_CHECKING: - from .models import Status - - -class Author(TypedDict, total=False): - """Author model with a custom XML name. - - :ivar name: Required. - :vartype name: str - """ - - name: Required[str] - """Required.""" - - -class Book(TypedDict, total=False): - """Book model with a custom XML name. - - :ivar title: Required. - :vartype title: str - """ - - title: Required[str] - """Required.""" - - -class ModelWithArrayOfModel(TypedDict, total=False): - """§4.1 — Contains an array of models. - - :ivar items_property: Required. - :vartype items_property: ~payload.xml.models.SimpleModel - """ - - items: Required[list["SimpleModel"]] - """Required.""" - - -class ModelWithAttributes(TypedDict, total=False): - """§5.1 — Contains fields that are XML attributes. - - :ivar id1: Required. - :vartype id1: int - :ivar id2: Required. - :vartype id2: str - :ivar enabled: Required. - :vartype enabled: bool - """ - - id1: Required[int] - """Required.""" - id2: Required[str] - """Required.""" - enabled: Required[bool] - """Required.""" - - -class ModelWithDatetime(TypedDict, total=False): - """Contains datetime properties with different encodings. - - :ivar rfc3339: DateTime value with rfc3339 encoding. Required. - :vartype rfc3339: ~datetime.datetime - :ivar rfc7231: DateTime value with rfc7231 encoding. Required. - :vartype rfc7231: ~datetime.datetime - """ - - rfc3339: Required[datetime.datetime] - """DateTime value with rfc3339 encoding. Required.""" - rfc7231: Required[datetime.datetime] - """DateTime value with rfc7231 encoding. Required.""" - - -class ModelWithDictionary(TypedDict, total=False): - """Contains a dictionary of key value pairs. - - :ivar metadata: Required. - :vartype metadata: dict[str, str] - """ - - metadata: Required[dict[str, str]] - """Required.""" - - -class ModelWithEmptyArray(TypedDict, total=False): - """Contains an array of models that's supposed to be sent/received as an empty XML element. - - :ivar items_property: Required. - :vartype items_property: ~payload.xml.models.SimpleModel - """ - - items: Required[list["SimpleModel"]] - """Required.""" - - -class ModelWithEncodedNames(TypedDict, total=False): - """Uses encodedName instead of Xml.Name which is functionally equivalent. - - :ivar model_data: Required. - :vartype model_data: ~payload.xml.models.SimpleModel - :ivar colors: Required. - :vartype colors: list[str] - """ - - modelData: Required["SimpleModel"] - """Required.""" - colors: Required[list[str]] - """Required.""" - - -class ModelWithEnum(TypedDict, total=False): - """Contains a single property with an enum value. - - :ivar status: Required. Known values are: "pending", "success", and "error". - :vartype status: str or ~payload.xml.models.Status - """ - - status: Required[Union[str, "Status"]] - """Required. Known values are: \"pending\", \"success\", and \"error\".""" - - -class ModelWithNamespace(TypedDict, total=False): - """§6.1, §7.1 — Contains fields with XML namespace on the model. - - :ivar id: Required. - :vartype id: int - :ivar title: Required. - :vartype title: str - """ - - id: Required[int] - """Required.""" - title: Required[str] - """Required.""" - - -class ModelWithNamespaceOnProperties(TypedDict, total=False): - """§6.2, §7.2 — Contains fields with different XML namespaces on individual properties. - - :ivar id: Required. - :vartype id: int - :ivar title: Required. - :vartype title: str - :ivar author: Required. - :vartype author: str - """ - - id: Required[int] - """Required.""" - title: Required[str] - """Required.""" - author: Required[str] - """Required.""" - - -class ModelWithNestedModel(TypedDict, total=False): - """§2.1 — Contains a property that references another model. - - :ivar nested: Required. - :vartype nested: ~payload.xml.models.SimpleModel - """ - - nested: Required["SimpleModel"] - """Required.""" - - -class ModelWithOptionalField(TypedDict, total=False): - """Contains an optional field. - - :ivar item: Required. - :vartype item: str - :ivar value: - :vartype value: int - """ - - item: Required[str] - """Required.""" - value: int - - -class ModelWithRenamedArrays(TypedDict, total=False): - """§3.3, §3.4 — Contains fields of wrapped and unwrapped arrays of primitive types that have - different XML representations. - - :ivar colors: Required. - :vartype colors: list[str] - :ivar counts: Required. - :vartype counts: list[int] - """ - - colors: Required[list[str]] - """Required.""" - counts: Required[list[int]] - """Required.""" - - -class ModelWithRenamedAttribute(TypedDict, total=False): - """§5.2 — Contains a renamed XML attribute. - - :ivar id: Required. - :vartype id: int - :ivar title: Required. - :vartype title: str - :ivar author: Required. - :vartype author: str - """ - - id: Required[int] - """Required.""" - title: Required[str] - """Required.""" - author: Required[str] - """Required.""" - - -class ModelWithRenamedFields(TypedDict, total=False): - """§1.3, §2.3 — Contains fields of the same type that have different XML representation. - - :ivar input_data: Required. - :vartype input_data: ~payload.xml.models.SimpleModel - :ivar output_data: Required. - :vartype output_data: ~payload.xml.models.SimpleModel - """ - - inputData: Required["SimpleModel"] - """Required.""" - outputData: Required["SimpleModel"] - """Required.""" - - -class ModelWithRenamedNestedModel(TypedDict, total=False): - """§2.2 — Contains a property whose type has. - - :ivar author: Required. - :vartype author: ~payload.xml.models.Author - """ - - author: Required["Author"] - """Required.""" - - -class ModelWithRenamedProperty(TypedDict, total=False): - """§1.2 — Contains a scalar property with a custom XML name. - - :ivar title: Required. - :vartype title: str - :ivar author: Required. - :vartype author: str - """ - - title: Required[str] - """Required.""" - author: Required[str] - """Required.""" - - -class ModelWithRenamedUnwrappedModelArray(TypedDict, total=False): - """§4.4 — Contains an unwrapped array of models with a custom item name. - - :ivar items_property: Required. - :vartype items_property: ~payload.xml.models.SimpleModel - """ - - items: Required[list["SimpleModel"]] - """Required.""" - - -class ModelWithRenamedWrappedAndItemModelArray(TypedDict, total=False): - """§4.5 — Contains a wrapped array of models with custom wrapper and item names. - - :ivar books: Required. - :vartype books: ~payload.xml.models.Book - """ - - books: Required[list["Book"]] - """Required.""" - - -class ModelWithRenamedWrappedModelArray(TypedDict, total=False): - """§4.3 — Contains a wrapped array of models with a custom wrapper name. - - :ivar items_property: Required. - :vartype items_property: ~payload.xml.models.SimpleModel - """ - - items: Required[list["SimpleModel"]] - """Required.""" - - -class ModelWithSimpleArrays(TypedDict, total=False): - """§3.1 — Contains fields of arrays of primitive types. - - :ivar colors: Required. - :vartype colors: list[str] - :ivar counts: Required. - :vartype counts: list[int] - """ - - colors: Required[list[str]] - """Required.""" - counts: Required[list[int]] - """Required.""" - - -class ModelWithText(TypedDict, total=False): - """§8.1 — Contains an attribute and text. - - :ivar language: Required. - :vartype language: str - :ivar content: Required. - :vartype content: str - """ - - language: Required[str] - """Required.""" - content: Required[str] - """Required.""" - - -class ModelWithUnwrappedArray(TypedDict, total=False): - """§3.2 — Contains fields of wrapped and unwrapped arrays of primitive types. - - :ivar colors: Required. - :vartype colors: list[str] - :ivar counts: Required. - :vartype counts: list[int] - """ - - colors: Required[list[str]] - """Required.""" - counts: Required[list[int]] - """Required.""" - - -class ModelWithUnwrappedModelArray(TypedDict, total=False): - """§4.2 — Contains an unwrapped array of models. - - :ivar items_property: Required. - :vartype items_property: ~payload.xml.models.SimpleModel - """ - - items: Required[list["SimpleModel"]] - """Required.""" - - -class ModelWithWrappedPrimitiveCustomItemNames(TypedDict, total=False): - """§3.5 — Contains a wrapped primitive array with custom wrapper and item names. - - :ivar tags: Required. - :vartype tags: list[str] - """ - - tags: Required[list[str]] - """Required.""" - - -class SimpleModel(TypedDict, total=False): - """§1.1 — Contains fields of primitive types. - - :ivar name: Required. - :vartype name: str - :ivar age: Required. - :vartype age: int - """ - - name: Required[str] - """Required.""" - age: Required[int] - """Required.""" - - -class XmlErrorBody(TypedDict, total=False): - """The body of an XML error response. - - :ivar message: Required. - :vartype message: str - :ivar code: Required. - :vartype code: int - """ - - message: Required[str] - """Required.""" - code: Required[int] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/pyproject.toml index 958fec5292c1..d2af28da07c6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/payload-xml/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/pyproject.toml index c8efc8d12c00..11bb91448218 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven1/resiliency/srv/driven1/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/pyproject.toml index d35ee8bfa48b..e1a81f5f3030 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/resiliency-srv-driven2/resiliency/srv/driven2/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/pyproject.toml index 4c973278fda3..da643e9ec4d0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/types.py deleted file mode 100644 index 5b4d7ab8bde4..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/response-status-code-range/response/statuscoderange/types.py +++ /dev/null @@ -1,61 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing_extensions import Required, TypedDict - - -class DefaultError(TypedDict, total=False): - """DefaultError. - - :ivar code: Required. - :vartype code: str - """ - - code: Required[str] - """Required.""" - - -class ErrorInRange(TypedDict, total=False): - """ErrorInRange. - - :ivar code: Required. - :vartype code: str - :ivar message: Required. - :vartype message: str - """ - - code: Required[str] - """Required.""" - message: Required[str] - """Required.""" - - -class NotFoundError(TypedDict, total=False): - """NotFoundError. - - :ivar code: Required. - :vartype code: str - :ivar resource_id: Required. - :vartype resource_id: str - """ - - code: Required[str] - """Required.""" - resourceId: Required[str] - """Required.""" - - -class Standard4XXError(TypedDict, total=False): - """Standard4XXError. - - :ivar code: Required. - :vartype code: str - """ - - code: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/apiview-properties.json index b2eb24eb9aa6..3a67981ca775 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/apiview-properties.json +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/apiview-properties.json @@ -1,6 +1,7 @@ { "CrossLanguagePackageId": "Routes", "CrossLanguageDefinitionId": { + "routes.models.ExpandParameters": "Routes.ExpandParameters", "routes.operations.PathParametersOperations.template_only": "Routes.PathParameters.templateOnly", "routes.aio.operations.PathParametersOperations.template_only": "Routes.PathParameters.templateOnly", "routes.operations.PathParametersOperations.explicit": "Routes.PathParameters.explicit", @@ -18,5 +19,5 @@ "routes.RoutesClient.fixed": "Routes.fixed", "routes.aio.RoutesClient.fixed": "Routes.fixed" }, - "CrossLanguageVersion": "61e0326a00d1" + "CrossLanguageVersion": "c6a64c6e889c" } \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/generated_tests/test_routes_query_parameters_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/generated_tests/test_routes_query_parameters_operations.py index 566ff148af5b..5c36474e7dc3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/generated_tests/test_routes_query_parameters_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/generated_tests/test_routes_query_parameters_operations.py @@ -111,6 +111,17 @@ def test_query_parameters_query_expansion_explode_record(self, routes_endpoint): # please add some check logic here by yourself # ... + @RoutesPreparer() + @recorded_by_proxy + def test_query_parameters_query_expansion_explode_model(self, routes_endpoint): + client = self.create_client(endpoint=routes_endpoint) + response = client.query_parameters.query_expansion.explode.model( + param={"field": "str", "value": "str"}, + ) + + # please add some check logic here by yourself + # ... + @RoutesPreparer() @recorded_by_proxy def test_query_parameters_query_continuation_standard_primitive(self, routes_endpoint): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/generated_tests/test_routes_query_parameters_operations_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/generated_tests/test_routes_query_parameters_operations_async.py index c85cfc7ebd74..a6d45e02bf3d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/generated_tests/test_routes_query_parameters_operations_async.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/generated_tests/test_routes_query_parameters_operations_async.py @@ -112,6 +112,17 @@ async def test_query_parameters_query_expansion_explode_record(self, routes_endp # please add some check logic here by yourself # ... + @RoutesPreparer() + @recorded_by_proxy_async + async def test_query_parameters_query_expansion_explode_model(self, routes_endpoint): + client = self.create_async_client(endpoint=routes_endpoint) + response = await client.query_parameters.query_expansion.explode.model( + param={"field": "str", "value": "str"}, + ) + + # please add some check logic here by yourself + # ... + @RoutesPreparer() @recorded_by_proxy_async async def test_query_parameters_query_continuation_standard_primitive(self, routes_endpoint): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/pyproject.toml index d07e7524e038..49f9962daff7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/models/__init__.py new file mode 100644 index 000000000000..32f742e4e8d2 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/models/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + ExpandParameters, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ExpandParameters", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/models/_models.py new file mode 100644 index 000000000000..4fc20fe9d662 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/models/_models.py @@ -0,0 +1,45 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +from typing import Any, Mapping, overload + +from .._utils.model_base import Model as _Model, rest_field + + +class ExpandParameters(_Model): + """A named model used to verify explode expansion of a model-valued query parameter. + + :ivar field: Required. + :vartype field: str + :ivar value: Required. + :vartype value: str + """ + + field: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + value: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + field: str, + value: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/explode/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/explode/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/explode/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/explode/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/standard/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/standard/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/standard/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/labelexpansion/standard/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/explode/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/explode/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/explode/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/explode/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/standard/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/standard/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/standard/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/matrixexpansion/standard/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/explode/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/explode/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/explode/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/explode/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/standard/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/standard/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/standard/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/pathexpansion/standard/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/reservedexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/reservedexpansion/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/reservedexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/reservedexpansion/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/reservedexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/reservedexpansion/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/reservedexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/reservedexpansion/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/explode/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/explode/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/explode/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/explode/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/standard/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/standard/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/standard/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/pathparameters/simpleexpansion/standard/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/explode/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/explode/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/explode/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/explode/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/standard/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/standard/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/standard/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/querycontinuation/standard/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_operations.py index 72e57055f54f..b6e4437cbf5c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_operations.py @@ -21,10 +21,12 @@ from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async +from ...... import models as _models5 from ......_utils.serialization import Deserializer, Serializer from ......aio._configuration import RoutesClientConfiguration from ...operations._operations import ( build_query_parameters_query_expansion_explode_array_request, + build_query_parameters_query_expansion_explode_model_request, build_query_parameters_query_expansion_explode_primitive_request, build_query_parameters_query_expansion_explode_record_request, ) @@ -190,3 +192,50 @@ async def record(self, *, param: dict[str, int], **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def model(self, *, param: _models5.ExpandParameters, **kwargs: Any) -> None: + """model. + + :keyword param: Required. + :paramtype param: ~routes.models.ExpandParameters + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_query_parameters_query_expansion_explode_model_request( + param=param, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/operations/_operations.py index 4d2eab7ae385..fe4f33cf75b0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/operations/_operations.py @@ -22,6 +22,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict +from ..... import models as _models4 from ....._configuration import RoutesClientConfiguration from ....._utils.serialization import Deserializer, Serializer @@ -74,6 +75,20 @@ def build_query_parameters_query_expansion_explode_record_request( # pylint: di return HttpRequest(method="GET", url=_url, params=_params, **kwargs) +def build_query_parameters_query_expansion_explode_model_request( # pylint: disable=name-too-long + *, param: _models4.ExpandParameters, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/routes/query/query-expansion/explode/model" + + # Construct parameters + _params["param"] = _SERIALIZER.query("param", param, "ExpandParameters") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + class QueryParametersQueryExpansionExplodeOperations: # pylint: disable=name-too-long """ .. warning:: @@ -231,3 +246,52 @@ def record(self, *, param: dict[str, int], **kwargs: Any) -> None: # pylint: di if cls: return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def model( # pylint: disable=inconsistent-return-statements + self, *, param: _models4.ExpandParameters, **kwargs: Any + ) -> None: + """model. + + :keyword param: Required. + :paramtype param: ~routes.models.ExpandParameters + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_query_parameters_query_expansion_explode_model_request( + param=param, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/explode/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/standard/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/standard/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/standard/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/routes/routes/queryparameters/queryexpansion/standard/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/pyproject.toml index 5b9d45a40fbb..95c1dd0fac70 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/operations/_operations.py index 2cbeb38e7e2f..df51f14cc04e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import build_property_get_request, build_property_send_request from .._configuration import JsonClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -71,11 +70,13 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send( + self, body: _types.JsonEncodedNameModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~serialization.encodedname.json.types.JsonEncodedNameModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -99,11 +100,14 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def send(self, body: Union[_models.JsonEncodedNameModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def send( + self, body: Union[_models.JsonEncodedNameModel, _types.JsonEncodedNameModel, IO[bytes]], **kwargs: Any + ) -> None: """send. - :param body: Is one of the following types: JsonEncodedNameModel, JSON, IO[bytes] Required. - :type body: ~serialization.encodedname.json.models.JsonEncodedNameModel or JSON or IO[bytes] + :param body: Is either a JsonEncodedNameModel type or a IO[bytes] type. Required. + :type body: ~serialization.encodedname.json.models.JsonEncodedNameModel or + ~serialization.encodedname.json.types.JsonEncodedNameModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/operations/_operations.py index d81793945068..2550363c9fb1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/operations/_operations.py @@ -26,12 +26,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import JsonClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -101,11 +100,11 @@ def send( """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.JsonEncodedNameModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~serialization.encodedname.json.types.JsonEncodedNameModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -130,12 +129,13 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.JsonEncodedNameModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.JsonEncodedNameModel, _types.JsonEncodedNameModel, IO[bytes]], **kwargs: Any ) -> None: """send. - :param body: Is one of the following types: JsonEncodedNameModel, JSON, IO[bytes] Required. - :type body: ~serialization.encodedname.json.models.JsonEncodedNameModel or JSON or IO[bytes] + :param body: Is either a JsonEncodedNameModel type or a IO[bytes] type. Required. + :type body: ~serialization.encodedname.json.models.JsonEncodedNameModel or + ~serialization.encodedname.json.types.JsonEncodedNameModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/serialization-encoded-name-json/serialization/encodedname/json/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/pyproject.toml index 0cd8a1a72165..0138056661ea 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-endpoint-not-defined/server/endpoint/notdefined/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/pyproject.toml index 5a72365a5617..fcb69f1d7644 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-multiple/server/path/multiple/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/pyproject.toml index a25c659cde4c..40d84f9db060 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-path-single/server/path/single/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/pyproject.toml index 324ba3752c50..471499f5edbf 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-not-versioned/server/versions/notversioned/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/pyproject.toml index 1a9c37f71469..b66da3c26af9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/server-versions-versioned/server/versions/versioned/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/pyproject.toml index 9f19b514459c..7a3821bfb602 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multi-service/service/multiservice/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/README.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/apiview-properties.json index 513d35da7908..74d00851efb4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/apiview-properties.json +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/apiview-properties.json @@ -11,5 +11,6 @@ "service.multipleservices.servicea.aio.operations.SubNamespaceOperations.sub_op_b": "Service.MultipleServices.ServiceB.SubNamespace.subOpB", "service.multipleservices.servicea.operations.Operations.op_b": "Service.MultipleServices.ServiceB.Operations.opB", "service.multipleservices.servicea.aio.operations.Operations.op_b": "Service.MultipleServices.ServiceB.Operations.opB" - } + }, + "CrossLanguageVersion": "906e2172ff3b" } \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/pyproject.toml index 54c9d90c5929..f42596fafcf0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/pyproject.toml @@ -21,13 +21,13 @@ classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] -requires-python = ">=3.9" +requires-python = ">=3.10" keywords = ["azure", "azure sdk"] dependencies = [ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_client.py index 23a56f017bec..6948e5d94f6f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_client.py @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any -from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies @@ -19,6 +19,11 @@ from .operations import Operations from .subnamespace.operations import SubNamespaceOperations +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + class ServiceAClient: """First service definition in a multiple-services package with versioning. Without explicit @@ -30,8 +35,9 @@ class ServiceAClient: :vartype operations: service.multipleservices.servicea.operations.Operations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str - :keyword api_version: Known values are "av2". Default value is "av2". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Known values are "av2" and None. Default value is None. If not set, the + operation's default API version will be used. Note that overriding this default value may + result in unsupported behavior. :paramtype api_version: str or ~service.multipleservices.servicea.models.VersionsA """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_configuration.py index ba4388db9a14..35aa22578f5e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_configuration.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_configuration.py @@ -21,8 +21,9 @@ class ServiceAClientConfiguration: # pylint: disable=too-many-instance-attribut :param endpoint: Service host. Default value is "http://localhost:3000". :type endpoint: str - :keyword api_version: Known values are "av2". Default value is "av2". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Known values are "av2" and None. Default value is None. If not set, the + operation's default API version will be used. Note that overriding this default value may + result in unsupported behavior. :paramtype api_version: str or ~service.multipleservices.servicea.models.VersionsA """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_utils/model_base.py index db24930fdca9..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_utils/model_base.py @@ -23,14 +23,19 @@ from json import JSONEncoder import xml.etree.ElementTree as ET from collections.abc import MutableMapping -from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError from azure.core import CaseInsensitiveEnumMeta from azure.core.pipeline import PipelineResponse from azure.core.serialization import _Null + from azure.core.rest import HttpResponse +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _LOGGER = logging.getLogger(__name__) __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] @@ -104,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -296,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -325,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -420,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -444,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -479,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -504,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -559,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass @@ -585,6 +624,239 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin return _serialize(value, rf._format) +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param class Model(_MyMutableMapping): _is_model = True # label whether current class's _attr_to_rest_field has been calculated @@ -595,11 +867,7 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: class_name = self.__class__.__name__ if len(args) > 1: raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") - dict_to_pass = { - rest_field._rest_name: rest_field._default - for rest_field in self._attr_to_rest_field.values() - if rest_field._default is not _UNSET - } + dict_to_pass: dict[str, typing.Any] = {} if args: if isinstance(args[0], ET.Element): dict_to_pass.update(self._init_from_xml(args[0])) @@ -619,9 +887,19 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if v is not None } ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) super().__init__(dict_to_pass) - def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + self, element: ET.Element + ) -> dict[str, typing.Any]: """Deserialize an XML element into a dict mapping rest field names to values. :param ET.Element element: The XML element to deserialize from. @@ -629,53 +907,89 @@ def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: :rtype: dict """ result: dict[str, typing.Any] = {} - model_meta = getattr(self, "_xml", {}) existed_attr_keys: list[str] = [] - for rf in self._attr_to_rest_field.values(): - prop_meta = getattr(rf, "_xml", {}) - xml_name = prop_meta.get("name", rf._rest_name) - xml_ns = _resolve_xml_ns(prop_meta, model_meta) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - # attribute - if prop_meta.get("attribute", False) and element.get(xml_name) is not None: - existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) - continue - - # unwrapped element is array - if prop_meta.get("unwrapped", False): - # unwrapped array could either use prop items meta/prop meta - _items_name = prop_meta.get("itemsName") - if _items_name: - xml_name = _items_name - _items_ns = prop_meta.get("itemsNs") - if _items_ns is not None: - xml_ns = _items_ns - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - items = element.findall(xml_name) # pyright: ignore - if len(items) > 0: + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, items) - elif not rf._is_optional: + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array + item = element.find(xml_name) + if item is not None: existed_attr_keys.append(xml_name) - result[rf._rest_name] = [] - continue - - # text element is primitive type - if prop_meta.get("text", False): - if element.text is not None: - result[rf._rest_name] = _deserialize(rf._type, element.text) - continue - - # wrapped element could be normal property or array, it should only have one element - item = element.find(xml_name) - if item is not None: - existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, item) + result[rf._rest_name] = _deserialize(rf._type, item) # rest thing is additional properties for e in element: @@ -708,6 +1022,9 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -1082,6 +1399,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, ): self._type = type self._rest_name_input = name @@ -1094,6 +1412,7 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._deserializer = deserializer @property def _class_type(self) -> typing.Any: @@ -1113,7 +1432,10 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class # Use _data.get() directly to avoid triggering __getitem__ which clears the cache - item = obj._data.get(self._rest_name) + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None if item is None: return item if self._is_model: @@ -1126,7 +1448,11 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # Return the value from _data directly (it's been deserialized in place) return obj._data.get(self._rest_name) - deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) # For mutable types, store the deserialized value back in _data # so mutations directly affect _data @@ -1172,6 +1498,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, ) -> typing.Any: return _RestField( name=name, @@ -1181,6 +1508,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + deserializer=deserializer, ) @@ -1414,6 +1742,8 @@ def _deserialize_xml( value: str, ) -> typing.Any: element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) return _deserialize(deserializer, element) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_utils/serialization.py index 81ec1de5922b..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/_utils/serialization.py @@ -39,11 +39,15 @@ import xml.etree.ElementTree as ET import isodate # type: ignore -from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") JSON = MutableMapping[str, Any] @@ -516,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1105,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1377,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1389,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1401,7 +1472,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: # Otherwise, result are unexpected self.additional_properties_detection = True - def __call__(self, target_obj, response_data, content_type=None): + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements """Call the deserializer to process a REST response. :param str target_obj: Target data type to deserialize to. @@ -1411,6 +1482,27 @@ def __call__(self, target_obj, response_data, content_type=None): :return: Deserialized object. :rtype: object """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) @@ -1929,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/aio/_client.py index e8a01b87377b..b69b398f2958 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/aio/_client.py @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any, Awaitable -from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.pipeline import policies @@ -19,6 +19,11 @@ from ._configuration import ServiceAClientConfiguration from .operations import Operations +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + class ServiceAClient: """First service definition in a multiple-services package with versioning. Without explicit @@ -30,8 +35,9 @@ class ServiceAClient: :vartype operations: service.multipleservices.servicea.aio.operations.Operations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str - :keyword api_version: Known values are "av2". Default value is "av2". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Known values are "av2" and None. Default value is None. If not set, the + operation's default API version will be used. Note that overriding this default value may + result in unsupported behavior. :paramtype api_version: str or ~service.multipleservices.servicea.models.VersionsA """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/aio/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/aio/_configuration.py index 5f5ea14616ad..5a6b43ee1944 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/aio/_configuration.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/servicea/aio/_configuration.py @@ -21,8 +21,9 @@ class ServiceAClientConfiguration: # pylint: disable=too-many-instance-attribut :param endpoint: Service host. Default value is "http://localhost:3000". :type endpoint: str - :keyword api_version: Known values are "av2". Default value is "av2". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Known values are "av2" and None. Default value is None. If not set, the + operation's default API version will be used. Note that overriding this default value may + result in unsupported behavior. :paramtype api_version: str or ~service.multipleservices.servicea.models.VersionsA """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_client.py index c0037584b576..4ea934236f8b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_client.py @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any -from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies @@ -19,6 +19,11 @@ from .operations import Operations from .subnamespace.operations import SubNamespaceOperations +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + class ServiceBClient: """Second service definition in a multiple-services package with versioning. Without explicit @@ -30,8 +35,9 @@ class ServiceBClient: :vartype operations: service.multipleservices.servicea.operations.Operations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str - :keyword api_version: Known values are "bv2". Default value is "bv2". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Known values are "bv2" and None. Default value is None. If not set, the + operation's default API version will be used. Note that overriding this default value may + result in unsupported behavior. :paramtype api_version: str or ~service.multipleservices.serviceb.models.VersionsB """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_configuration.py index 7f3d9b5fcbe2..dfecfc2062a6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_configuration.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_configuration.py @@ -21,8 +21,9 @@ class ServiceBClientConfiguration: # pylint: disable=too-many-instance-attribut :param endpoint: Service host. Default value is "http://localhost:3000". :type endpoint: str - :keyword api_version: Known values are "bv2". Default value is "bv2". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Known values are "bv2" and None. Default value is None. If not set, the + operation's default API version will be used. Note that overriding this default value may + result in unsupported behavior. :paramtype api_version: str or ~service.multipleservices.serviceb.models.VersionsB """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_utils/model_base.py index db24930fdca9..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_utils/model_base.py @@ -23,14 +23,19 @@ from json import JSONEncoder import xml.etree.ElementTree as ET from collections.abc import MutableMapping -from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError from azure.core import CaseInsensitiveEnumMeta from azure.core.pipeline import PipelineResponse from azure.core.serialization import _Null + from azure.core.rest import HttpResponse +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _LOGGER = logging.getLogger(__name__) __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] @@ -104,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -296,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -325,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -420,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -444,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -479,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -504,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -559,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass @@ -585,6 +624,239 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin return _serialize(value, rf._format) +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param class Model(_MyMutableMapping): _is_model = True # label whether current class's _attr_to_rest_field has been calculated @@ -595,11 +867,7 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: class_name = self.__class__.__name__ if len(args) > 1: raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") - dict_to_pass = { - rest_field._rest_name: rest_field._default - for rest_field in self._attr_to_rest_field.values() - if rest_field._default is not _UNSET - } + dict_to_pass: dict[str, typing.Any] = {} if args: if isinstance(args[0], ET.Element): dict_to_pass.update(self._init_from_xml(args[0])) @@ -619,9 +887,19 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if v is not None } ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) super().__init__(dict_to_pass) - def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + self, element: ET.Element + ) -> dict[str, typing.Any]: """Deserialize an XML element into a dict mapping rest field names to values. :param ET.Element element: The XML element to deserialize from. @@ -629,53 +907,89 @@ def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: :rtype: dict """ result: dict[str, typing.Any] = {} - model_meta = getattr(self, "_xml", {}) existed_attr_keys: list[str] = [] - for rf in self._attr_to_rest_field.values(): - prop_meta = getattr(rf, "_xml", {}) - xml_name = prop_meta.get("name", rf._rest_name) - xml_ns = _resolve_xml_ns(prop_meta, model_meta) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - # attribute - if prop_meta.get("attribute", False) and element.get(xml_name) is not None: - existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) - continue - - # unwrapped element is array - if prop_meta.get("unwrapped", False): - # unwrapped array could either use prop items meta/prop meta - _items_name = prop_meta.get("itemsName") - if _items_name: - xml_name = _items_name - _items_ns = prop_meta.get("itemsNs") - if _items_ns is not None: - xml_ns = _items_ns - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - items = element.findall(xml_name) # pyright: ignore - if len(items) > 0: + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, items) - elif not rf._is_optional: + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array + item = element.find(xml_name) + if item is not None: existed_attr_keys.append(xml_name) - result[rf._rest_name] = [] - continue - - # text element is primitive type - if prop_meta.get("text", False): - if element.text is not None: - result[rf._rest_name] = _deserialize(rf._type, element.text) - continue - - # wrapped element could be normal property or array, it should only have one element - item = element.find(xml_name) - if item is not None: - existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, item) + result[rf._rest_name] = _deserialize(rf._type, item) # rest thing is additional properties for e in element: @@ -708,6 +1022,9 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -1082,6 +1399,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, ): self._type = type self._rest_name_input = name @@ -1094,6 +1412,7 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._deserializer = deserializer @property def _class_type(self) -> typing.Any: @@ -1113,7 +1432,10 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class # Use _data.get() directly to avoid triggering __getitem__ which clears the cache - item = obj._data.get(self._rest_name) + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None if item is None: return item if self._is_model: @@ -1126,7 +1448,11 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # Return the value from _data directly (it's been deserialized in place) return obj._data.get(self._rest_name) - deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) # For mutable types, store the deserialized value back in _data # so mutations directly affect _data @@ -1172,6 +1498,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, ) -> typing.Any: return _RestField( name=name, @@ -1181,6 +1508,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + deserializer=deserializer, ) @@ -1414,6 +1742,8 @@ def _deserialize_xml( value: str, ) -> typing.Any: element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) return _deserialize(deserializer, element) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_utils/serialization.py index 81ec1de5922b..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/_utils/serialization.py @@ -39,11 +39,15 @@ import xml.etree.ElementTree as ET import isodate # type: ignore -from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") JSON = MutableMapping[str, Any] @@ -516,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1105,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1377,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1389,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1401,7 +1472,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: # Otherwise, result are unexpected self.additional_properties_detection = True - def __call__(self, target_obj, response_data, content_type=None): + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements """Call the deserializer to process a REST response. :param str target_obj: Target data type to deserialize to. @@ -1411,6 +1482,27 @@ def __call__(self, target_obj, response_data, content_type=None): :return: Deserialized object. :rtype: object """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) @@ -1929,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/aio/_client.py index 3521dc4f1950..50ec018ec8ee 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/aio/_client.py @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any, Awaitable -from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.pipeline import policies @@ -19,6 +19,11 @@ from ._configuration import ServiceBClientConfiguration from .operations import Operations +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + class ServiceBClient: """Second service definition in a multiple-services package with versioning. Without explicit @@ -30,8 +35,9 @@ class ServiceBClient: :vartype operations: service.multipleservices.servicea.aio.operations.Operations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str - :keyword api_version: Known values are "bv2". Default value is "bv2". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Known values are "bv2" and None. Default value is None. If not set, the + operation's default API version will be used. Note that overriding this default value may + result in unsupported behavior. :paramtype api_version: str or ~service.multipleservices.serviceb.models.VersionsB """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/aio/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/aio/_configuration.py index a604e664ae13..8843508302fe 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/aio/_configuration.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/service-multiple-services/service/multipleservices/serviceb/aio/_configuration.py @@ -21,8 +21,9 @@ class ServiceBClientConfiguration: # pylint: disable=too-many-instance-attribut :param endpoint: Service host. Default value is "http://localhost:3000". :type endpoint: str - :keyword api_version: Known values are "bv2". Default value is "bv2". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Known values are "bv2" and None. Default value is None. If not set, the + operation's default API version will be used. Note that overriding this default value may + result in unsupported behavior. :paramtype api_version: str or ~service.multipleservices.serviceb.models.VersionsB """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setup.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setup.py index e7bac7cdea4b..93cf05383d51 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setup.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setup.py @@ -47,6 +47,7 @@ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "License :: OSI Approved :: MIT License", ], zip_safe=False, diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/setuppy-authentication-union/setuppy/authentication/union/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/pyproject.toml index d4e8c21dff55..784a40e92b93 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/pyproject.toml index f6fe56670f32..8caab830156a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-headers-repeatability/specialheaders/repeatability/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/pyproject.toml index 68d3ec30e267..3fa1794c4ef2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_client.py index 1d6f7fc84658..360b661cfb2e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_client.py @@ -72,7 +72,7 @@ class SpecialWordsClient: # pylint: disable=client-accepts-api-version-keyword try while with - yield. + yield :ivar models: ModelsOperations operations :vartype models: specialwords.operations.ModelsOperations diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_utils/model_base.py index bd5b9caf1022..1934415c1369 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/_client.py index 94922f35b3fa..500198dd6a65 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/_client.py @@ -72,7 +72,7 @@ class SpecialWordsClient: # pylint: disable=client-accepts-api-version-keyword try while with - yield. + yield :ivar models: ModelsOperations operations :vartype models: specialwords.aio.operations.ModelsOperations diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/operations/_operations.py index 4d54d9768f84..74a699b45419 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -139,9 +139,9 @@ ) from .._configuration import SpecialWordsClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] _Unset: Any = object() @@ -177,11 +177,11 @@ async def with_and(self, body: _models.AndModel, *, content_type: str = "applica """ @overload - async def with_and(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_and(self, body: _types.AndModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_and. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.AndModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -205,11 +205,11 @@ async def with_and(self, body: IO[bytes], *, content_type: str = "application/js """ @distributed_trace_async - async def with_and(self, body: Union[_models.AndModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_and(self, body: Union[_models.AndModel, _types.AndModel, IO[bytes]], **kwargs: Any) -> None: """with_and. - :param body: Is one of the following types: AndModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.AndModel or JSON or IO[bytes] + :param body: Is either a AndModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.AndModel or ~specialwords.types.AndModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -275,11 +275,11 @@ async def with_as(self, body: _models.AsModel, *, content_type: str = "applicati """ @overload - async def with_as(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_as(self, body: _types.AsModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_as. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.AsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -303,11 +303,11 @@ async def with_as(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def with_as(self, body: Union[_models.AsModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_as(self, body: Union[_models.AsModel, _types.AsModel, IO[bytes]], **kwargs: Any) -> None: """with_as. - :param body: Is one of the following types: AsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.AsModel or JSON or IO[bytes] + :param body: Is either a AsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.AsModel or ~specialwords.types.AsModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -375,11 +375,13 @@ async def with_assert( """ @overload - async def with_assert(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_assert( + self, body: _types.AssertModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_assert. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.AssertModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -403,11 +405,11 @@ async def with_assert(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def with_assert(self, body: Union[_models.AssertModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_assert(self, body: Union[_models.AssertModel, _types.AssertModel, IO[bytes]], **kwargs: Any) -> None: """with_assert. - :param body: Is one of the following types: AssertModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.AssertModel or JSON or IO[bytes] + :param body: Is either a AssertModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.AssertModel or ~specialwords.types.AssertModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -475,11 +477,13 @@ async def with_async( """ @overload - async def with_async(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_async( + self, body: _types.AsyncModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_async. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.AsyncModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -503,11 +507,11 @@ async def with_async(self, body: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def with_async(self, body: Union[_models.AsyncModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_async(self, body: Union[_models.AsyncModel, _types.AsyncModel, IO[bytes]], **kwargs: Any) -> None: """with_async. - :param body: Is one of the following types: AsyncModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.AsyncModel or JSON or IO[bytes] + :param body: Is either a AsyncModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.AsyncModel or ~specialwords.types.AsyncModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -575,11 +579,13 @@ async def with_await( """ @overload - async def with_await(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_await( + self, body: _types.AwaitModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_await. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.AwaitModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -603,11 +609,11 @@ async def with_await(self, body: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def with_await(self, body: Union[_models.AwaitModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_await(self, body: Union[_models.AwaitModel, _types.AwaitModel, IO[bytes]], **kwargs: Any) -> None: """with_await. - :param body: Is one of the following types: AwaitModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.AwaitModel or JSON or IO[bytes] + :param body: Is either a AwaitModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.AwaitModel or ~specialwords.types.AwaitModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -675,11 +681,13 @@ async def with_break( """ @overload - async def with_break(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_break( + self, body: _types.BreakModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_break. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.BreakModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -703,11 +711,11 @@ async def with_break(self, body: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def with_break(self, body: Union[_models.BreakModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_break(self, body: Union[_models.BreakModel, _types.BreakModel, IO[bytes]], **kwargs: Any) -> None: """with_break. - :param body: Is one of the following types: BreakModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.BreakModel or JSON or IO[bytes] + :param body: Is either a BreakModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.BreakModel or ~specialwords.types.BreakModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -775,11 +783,13 @@ async def with_class( """ @overload - async def with_class(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_class( + self, body: _types.ClassModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_class. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ClassModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -803,11 +813,11 @@ async def with_class(self, body: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def with_class(self, body: Union[_models.ClassModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_class(self, body: Union[_models.ClassModel, _types.ClassModel, IO[bytes]], **kwargs: Any) -> None: """with_class. - :param body: Is one of the following types: ClassModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ClassModel or JSON or IO[bytes] + :param body: Is either a ClassModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ClassModel or ~specialwords.types.ClassModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -875,11 +885,13 @@ async def with_constructor( """ @overload - async def with_constructor(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_constructor( + self, body: _types.Constructor, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_constructor. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.Constructor :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -903,11 +915,13 @@ async def with_constructor(self, body: IO[bytes], *, content_type: str = "applic """ @distributed_trace_async - async def with_constructor(self, body: Union[_models.Constructor, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_constructor( + self, body: Union[_models.Constructor, _types.Constructor, IO[bytes]], **kwargs: Any + ) -> None: """with_constructor. - :param body: Is one of the following types: Constructor, JSON, IO[bytes] Required. - :type body: ~specialwords.models.Constructor or JSON or IO[bytes] + :param body: Is either a Constructor type or a IO[bytes] type. Required. + :type body: ~specialwords.models.Constructor or ~specialwords.types.Constructor or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -975,11 +989,13 @@ async def with_continue( """ @overload - async def with_continue(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_continue( + self, body: _types.ContinueModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_continue. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ContinueModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1003,11 +1019,14 @@ async def with_continue(self, body: IO[bytes], *, content_type: str = "applicati """ @distributed_trace_async - async def with_continue(self, body: Union[_models.ContinueModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_continue( + self, body: Union[_models.ContinueModel, _types.ContinueModel, IO[bytes]], **kwargs: Any + ) -> None: """with_continue. - :param body: Is one of the following types: ContinueModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ContinueModel or JSON or IO[bytes] + :param body: Is either a ContinueModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ContinueModel or ~specialwords.types.ContinueModel or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1073,11 +1092,11 @@ async def with_def(self, body: _models.DefModel, *, content_type: str = "applica """ @overload - async def with_def(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_def(self, body: _types.DefModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_def. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.DefModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1101,11 +1120,11 @@ async def with_def(self, body: IO[bytes], *, content_type: str = "application/js """ @distributed_trace_async - async def with_def(self, body: Union[_models.DefModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_def(self, body: Union[_models.DefModel, _types.DefModel, IO[bytes]], **kwargs: Any) -> None: """with_def. - :param body: Is one of the following types: DefModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.DefModel or JSON or IO[bytes] + :param body: Is either a DefModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.DefModel or ~specialwords.types.DefModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1171,11 +1190,11 @@ async def with_del(self, body: _models.DelModel, *, content_type: str = "applica """ @overload - async def with_del(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_del(self, body: _types.DelModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_del. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.DelModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1199,11 +1218,11 @@ async def with_del(self, body: IO[bytes], *, content_type: str = "application/js """ @distributed_trace_async - async def with_del(self, body: Union[_models.DelModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_del(self, body: Union[_models.DelModel, _types.DelModel, IO[bytes]], **kwargs: Any) -> None: """with_del. - :param body: Is one of the following types: DelModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.DelModel or JSON or IO[bytes] + :param body: Is either a DelModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.DelModel or ~specialwords.types.DelModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1271,11 +1290,11 @@ async def with_elif( """ @overload - async def with_elif(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_elif(self, body: _types.ElifModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_elif. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ElifModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1299,11 +1318,11 @@ async def with_elif(self, body: IO[bytes], *, content_type: str = "application/j """ @distributed_trace_async - async def with_elif(self, body: Union[_models.ElifModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_elif(self, body: Union[_models.ElifModel, _types.ElifModel, IO[bytes]], **kwargs: Any) -> None: """with_elif. - :param body: Is one of the following types: ElifModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ElifModel or JSON or IO[bytes] + :param body: Is either a ElifModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ElifModel or ~specialwords.types.ElifModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1371,11 +1390,11 @@ async def with_else( """ @overload - async def with_else(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_else(self, body: _types.ElseModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_else. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ElseModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1399,11 +1418,11 @@ async def with_else(self, body: IO[bytes], *, content_type: str = "application/j """ @distributed_trace_async - async def with_else(self, body: Union[_models.ElseModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_else(self, body: Union[_models.ElseModel, _types.ElseModel, IO[bytes]], **kwargs: Any) -> None: """with_else. - :param body: Is one of the following types: ElseModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ElseModel or JSON or IO[bytes] + :param body: Is either a ElseModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ElseModel or ~specialwords.types.ElseModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1471,11 +1490,13 @@ async def with_except( """ @overload - async def with_except(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_except( + self, body: _types.ExceptModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_except. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ExceptModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1499,11 +1520,11 @@ async def with_except(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def with_except(self, body: Union[_models.ExceptModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_except(self, body: Union[_models.ExceptModel, _types.ExceptModel, IO[bytes]], **kwargs: Any) -> None: """with_except. - :param body: Is one of the following types: ExceptModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ExceptModel or JSON or IO[bytes] + :param body: Is either a ExceptModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ExceptModel or ~specialwords.types.ExceptModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1571,11 +1592,11 @@ async def with_exec( """ @overload - async def with_exec(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_exec(self, body: _types.ExecModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_exec. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ExecModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1599,11 +1620,11 @@ async def with_exec(self, body: IO[bytes], *, content_type: str = "application/j """ @distributed_trace_async - async def with_exec(self, body: Union[_models.ExecModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_exec(self, body: Union[_models.ExecModel, _types.ExecModel, IO[bytes]], **kwargs: Any) -> None: """with_exec. - :param body: Is one of the following types: ExecModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ExecModel or JSON or IO[bytes] + :param body: Is either a ExecModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ExecModel or ~specialwords.types.ExecModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1671,11 +1692,13 @@ async def with_finally( """ @overload - async def with_finally(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_finally( + self, body: _types.FinallyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_finally. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.FinallyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1699,11 +1722,13 @@ async def with_finally(self, body: IO[bytes], *, content_type: str = "applicatio """ @distributed_trace_async - async def with_finally(self, body: Union[_models.FinallyModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_finally( + self, body: Union[_models.FinallyModel, _types.FinallyModel, IO[bytes]], **kwargs: Any + ) -> None: """with_finally. - :param body: Is one of the following types: FinallyModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.FinallyModel or JSON or IO[bytes] + :param body: Is either a FinallyModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.FinallyModel or ~specialwords.types.FinallyModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1769,11 +1794,11 @@ async def with_for(self, body: _models.ForModel, *, content_type: str = "applica """ @overload - async def with_for(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_for(self, body: _types.ForModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_for. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ForModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1797,11 +1822,11 @@ async def with_for(self, body: IO[bytes], *, content_type: str = "application/js """ @distributed_trace_async - async def with_for(self, body: Union[_models.ForModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_for(self, body: Union[_models.ForModel, _types.ForModel, IO[bytes]], **kwargs: Any) -> None: """with_for. - :param body: Is one of the following types: ForModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ForModel or JSON or IO[bytes] + :param body: Is either a ForModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ForModel or ~specialwords.types.ForModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1869,11 +1894,11 @@ async def with_from( """ @overload - async def with_from(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_from(self, body: _types.FromModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_from. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.FromModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1897,11 +1922,11 @@ async def with_from(self, body: IO[bytes], *, content_type: str = "application/j """ @distributed_trace_async - async def with_from(self, body: Union[_models.FromModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_from(self, body: Union[_models.FromModel, _types.FromModel, IO[bytes]], **kwargs: Any) -> None: """with_from. - :param body: Is one of the following types: FromModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.FromModel or JSON or IO[bytes] + :param body: Is either a FromModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.FromModel or ~specialwords.types.FromModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1969,11 +1994,13 @@ async def with_global( """ @overload - async def with_global(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_global( + self, body: _types.GlobalModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_global. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.GlobalModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1997,11 +2024,11 @@ async def with_global(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def with_global(self, body: Union[_models.GlobalModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_global(self, body: Union[_models.GlobalModel, _types.GlobalModel, IO[bytes]], **kwargs: Any) -> None: """with_global. - :param body: Is one of the following types: GlobalModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.GlobalModel or JSON or IO[bytes] + :param body: Is either a GlobalModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.GlobalModel or ~specialwords.types.GlobalModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2067,11 +2094,11 @@ async def with_if(self, body: _models.IfModel, *, content_type: str = "applicati """ @overload - async def with_if(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_if(self, body: _types.IfModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_if. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.IfModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2095,11 +2122,11 @@ async def with_if(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def with_if(self, body: Union[_models.IfModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_if(self, body: Union[_models.IfModel, _types.IfModel, IO[bytes]], **kwargs: Any) -> None: """with_if. - :param body: Is one of the following types: IfModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.IfModel or JSON or IO[bytes] + :param body: Is either a IfModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.IfModel or ~specialwords.types.IfModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2167,11 +2194,13 @@ async def with_import( """ @overload - async def with_import(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_import( + self, body: _types.ImportModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_import. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ImportModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2195,11 +2224,11 @@ async def with_import(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def with_import(self, body: Union[_models.ImportModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_import(self, body: Union[_models.ImportModel, _types.ImportModel, IO[bytes]], **kwargs: Any) -> None: """with_import. - :param body: Is one of the following types: ImportModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ImportModel or JSON or IO[bytes] + :param body: Is either a ImportModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ImportModel or ~specialwords.types.ImportModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2265,11 +2294,11 @@ async def with_in(self, body: _models.InModel, *, content_type: str = "applicati """ @overload - async def with_in(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_in(self, body: _types.InModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_in. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.InModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2293,11 +2322,11 @@ async def with_in(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def with_in(self, body: Union[_models.InModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_in(self, body: Union[_models.InModel, _types.InModel, IO[bytes]], **kwargs: Any) -> None: """with_in. - :param body: Is one of the following types: InModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.InModel or JSON or IO[bytes] + :param body: Is either a InModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.InModel or ~specialwords.types.InModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2363,11 +2392,11 @@ async def with_is(self, body: _models.IsModel, *, content_type: str = "applicati """ @overload - async def with_is(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_is(self, body: _types.IsModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_is. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.IsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2391,11 +2420,11 @@ async def with_is(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def with_is(self, body: Union[_models.IsModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_is(self, body: Union[_models.IsModel, _types.IsModel, IO[bytes]], **kwargs: Any) -> None: """with_is. - :param body: Is one of the following types: IsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.IsModel or JSON or IO[bytes] + :param body: Is either a IsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.IsModel or ~specialwords.types.IsModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2463,11 +2492,13 @@ async def with_lambda( """ @overload - async def with_lambda(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_lambda( + self, body: _types.LambdaModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_lambda. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.LambdaModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2491,11 +2522,11 @@ async def with_lambda(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def with_lambda(self, body: Union[_models.LambdaModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_lambda(self, body: Union[_models.LambdaModel, _types.LambdaModel, IO[bytes]], **kwargs: Any) -> None: """with_lambda. - :param body: Is one of the following types: LambdaModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.LambdaModel or JSON or IO[bytes] + :param body: Is either a LambdaModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.LambdaModel or ~specialwords.types.LambdaModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2561,11 +2592,11 @@ async def with_not(self, body: _models.NotModel, *, content_type: str = "applica """ @overload - async def with_not(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_not(self, body: _types.NotModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_not. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.NotModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2589,11 +2620,11 @@ async def with_not(self, body: IO[bytes], *, content_type: str = "application/js """ @distributed_trace_async - async def with_not(self, body: Union[_models.NotModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_not(self, body: Union[_models.NotModel, _types.NotModel, IO[bytes]], **kwargs: Any) -> None: """with_not. - :param body: Is one of the following types: NotModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.NotModel or JSON or IO[bytes] + :param body: Is either a NotModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.NotModel or ~specialwords.types.NotModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2659,11 +2690,11 @@ async def with_or(self, body: _models.OrModel, *, content_type: str = "applicati """ @overload - async def with_or(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_or(self, body: _types.OrModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_or. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.OrModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2687,11 +2718,11 @@ async def with_or(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def with_or(self, body: Union[_models.OrModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_or(self, body: Union[_models.OrModel, _types.OrModel, IO[bytes]], **kwargs: Any) -> None: """with_or. - :param body: Is one of the following types: OrModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.OrModel or JSON or IO[bytes] + :param body: Is either a OrModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.OrModel or ~specialwords.types.OrModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2759,11 +2790,11 @@ async def with_pass( """ @overload - async def with_pass(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_pass(self, body: _types.PassModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_pass. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.PassModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2787,11 +2818,11 @@ async def with_pass(self, body: IO[bytes], *, content_type: str = "application/j """ @distributed_trace_async - async def with_pass(self, body: Union[_models.PassModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_pass(self, body: Union[_models.PassModel, _types.PassModel, IO[bytes]], **kwargs: Any) -> None: """with_pass. - :param body: Is one of the following types: PassModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.PassModel or JSON or IO[bytes] + :param body: Is either a PassModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.PassModel or ~specialwords.types.PassModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2859,11 +2890,13 @@ async def with_raise( """ @overload - async def with_raise(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_raise( + self, body: _types.RaiseModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_raise. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.RaiseModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2887,11 +2920,11 @@ async def with_raise(self, body: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def with_raise(self, body: Union[_models.RaiseModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_raise(self, body: Union[_models.RaiseModel, _types.RaiseModel, IO[bytes]], **kwargs: Any) -> None: """with_raise. - :param body: Is one of the following types: RaiseModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.RaiseModel or JSON or IO[bytes] + :param body: Is either a RaiseModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.RaiseModel or ~specialwords.types.RaiseModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2959,11 +2992,13 @@ async def with_return( """ @overload - async def with_return(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_return( + self, body: _types.ReturnModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_return. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ReturnModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2987,11 +3022,11 @@ async def with_return(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def with_return(self, body: Union[_models.ReturnModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_return(self, body: Union[_models.ReturnModel, _types.ReturnModel, IO[bytes]], **kwargs: Any) -> None: """with_return. - :param body: Is one of the following types: ReturnModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ReturnModel or JSON or IO[bytes] + :param body: Is either a ReturnModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ReturnModel or ~specialwords.types.ReturnModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3057,11 +3092,11 @@ async def with_try(self, body: _models.TryModel, *, content_type: str = "applica """ @overload - async def with_try(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_try(self, body: _types.TryModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_try. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.TryModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3085,11 +3120,11 @@ async def with_try(self, body: IO[bytes], *, content_type: str = "application/js """ @distributed_trace_async - async def with_try(self, body: Union[_models.TryModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_try(self, body: Union[_models.TryModel, _types.TryModel, IO[bytes]], **kwargs: Any) -> None: """with_try. - :param body: Is one of the following types: TryModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.TryModel or JSON or IO[bytes] + :param body: Is either a TryModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.TryModel or ~specialwords.types.TryModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3157,11 +3192,13 @@ async def with_while( """ @overload - async def with_while(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_while( + self, body: _types.WhileModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_while. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.WhileModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3185,11 +3222,11 @@ async def with_while(self, body: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def with_while(self, body: Union[_models.WhileModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_while(self, body: Union[_models.WhileModel, _types.WhileModel, IO[bytes]], **kwargs: Any) -> None: """with_while. - :param body: Is one of the following types: WhileModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.WhileModel or JSON or IO[bytes] + :param body: Is either a WhileModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.WhileModel or ~specialwords.types.WhileModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3257,11 +3294,11 @@ async def with_with( """ @overload - async def with_with(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_with(self, body: _types.WithModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_with. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.WithModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3285,11 +3322,11 @@ async def with_with(self, body: IO[bytes], *, content_type: str = "application/j """ @distributed_trace_async - async def with_with(self, body: Union[_models.WithModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_with(self, body: Union[_models.WithModel, _types.WithModel, IO[bytes]], **kwargs: Any) -> None: """with_with. - :param body: Is one of the following types: WithModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.WithModel or JSON or IO[bytes] + :param body: Is either a WithModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.WithModel or ~specialwords.types.WithModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3357,11 +3394,13 @@ async def with_yield( """ @overload - async def with_yield(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_yield( + self, body: _types.YieldModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_yield. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.YieldModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3385,11 +3424,11 @@ async def with_yield(self, body: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def with_yield(self, body: Union[_models.YieldModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_yield(self, body: Union[_models.YieldModel, _types.YieldModel, IO[bytes]], **kwargs: Any) -> None: """with_yield. - :param body: Is one of the following types: YieldModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.YieldModel or JSON or IO[bytes] + :param body: Is either a YieldModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.YieldModel or ~specialwords.types.YieldModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3475,11 +3514,13 @@ async def same_as_model( """ @overload - async def same_as_model(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def same_as_model( + self, body: _types.SameAsModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """same_as_model. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.SameAsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3503,11 +3544,13 @@ async def same_as_model(self, body: IO[bytes], *, content_type: str = "applicati """ @distributed_trace_async - async def same_as_model(self, body: Union[_models.SameAsModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def same_as_model( + self, body: Union[_models.SameAsModel, _types.SameAsModel, IO[bytes]], **kwargs: Any + ) -> None: """same_as_model. - :param body: Is one of the following types: SameAsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.SameAsModel or JSON or IO[bytes] + :param body: Is either a SameAsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.SameAsModel or ~specialwords.types.SameAsModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3575,11 +3618,13 @@ async def dict_methods( """ @overload - async def dict_methods(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def dict_methods( + self, body: _types.DictMethods, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """dict_methods. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.DictMethods :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3603,11 +3648,13 @@ async def dict_methods(self, body: IO[bytes], *, content_type: str = "applicatio """ @distributed_trace_async - async def dict_methods(self, body: Union[_models.DictMethods, JSON, IO[bytes]], **kwargs: Any) -> None: + async def dict_methods( + self, body: Union[_models.DictMethods, _types.DictMethods, IO[bytes]], **kwargs: Any + ) -> None: """dict_methods. - :param body: Is one of the following types: DictMethods, JSON, IO[bytes] Required. - :type body: ~specialwords.models.DictMethods or JSON or IO[bytes] + :param body: Is either a DictMethods type or a IO[bytes] type. Required. + :type body: ~specialwords.models.DictMethods or ~specialwords.types.DictMethods or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3675,11 +3722,13 @@ async def with_list( """ @overload - async def with_list(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_list( + self, body: _types.ModelWithList, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_list. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ModelWithList :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3703,11 +3752,14 @@ async def with_list(self, body: IO[bytes], *, content_type: str = "application/j """ @distributed_trace_async - async def with_list(self, body: Union[_models.ModelWithList, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_list( + self, body: Union[_models.ModelWithList, _types.ModelWithList, IO[bytes]], **kwargs: Any + ) -> None: """with_list. - :param body: Is one of the following types: ModelWithList, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ModelWithList or JSON or IO[bytes] + :param body: Is either a ModelWithList type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ModelWithList or ~specialwords.types.ModelWithList or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3791,11 +3843,13 @@ async def with_items(self, *, items: list[str], content_type: str = "application """ @overload - async def with_items(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_items( + self, body: _types.WithItemsRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_items. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.WithItemsRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3820,12 +3874,16 @@ async def with_items(self, body: IO[bytes], *, content_type: str = "application/ @distributed_trace_async async def with_items( - self, body: Union[JSON, IO[bytes]] = _Unset, *, items: list[str] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.WithItemsRequest, IO[bytes]] = _Unset, + *, + items: list[str] = _Unset, + **kwargs: Any ) -> None: """with_items. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, WithItemsRequest, IO[bytes] Required. + :type body: JSON or ~specialwords.types.WithItemsRequest or IO[bytes] :keyword items: Required. :paramtype items: list[str] :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/operations/_operations.py index 344dd20b99c0..ed67a36d926a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/operations/_operations.py @@ -27,14 +27,14 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import SpecialWordsClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] _Unset: Any = object() _SERIALIZER = Serializer() @@ -1254,11 +1254,11 @@ def with_and(self, body: _models.AndModel, *, content_type: str = "application/j """ @overload - def with_and(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_and(self, body: _types.AndModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_and. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.AndModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1283,12 +1283,12 @@ def with_and(self, body: IO[bytes], *, content_type: str = "application/json", * @distributed_trace def with_and( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.AndModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.AndModel, _types.AndModel, IO[bytes]], **kwargs: Any ) -> None: """with_and. - :param body: Is one of the following types: AndModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.AndModel or JSON or IO[bytes] + :param body: Is either a AndModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.AndModel or ~specialwords.types.AndModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1354,11 +1354,11 @@ def with_as(self, body: _models.AsModel, *, content_type: str = "application/jso """ @overload - def with_as(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_as(self, body: _types.AsModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_as. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.AsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1383,12 +1383,12 @@ def with_as(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def with_as( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.AsModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.AsModel, _types.AsModel, IO[bytes]], **kwargs: Any ) -> None: """with_as. - :param body: Is one of the following types: AsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.AsModel or JSON or IO[bytes] + :param body: Is either a AsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.AsModel or ~specialwords.types.AsModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1454,11 +1454,11 @@ def with_assert(self, body: _models.AssertModel, *, content_type: str = "applica """ @overload - def with_assert(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_assert(self, body: _types.AssertModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_assert. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.AssertModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1483,12 +1483,12 @@ def with_assert(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def with_assert( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.AssertModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.AssertModel, _types.AssertModel, IO[bytes]], **kwargs: Any ) -> None: """with_assert. - :param body: Is one of the following types: AssertModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.AssertModel or JSON or IO[bytes] + :param body: Is either a AssertModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.AssertModel or ~specialwords.types.AssertModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1554,11 +1554,11 @@ def with_async(self, body: _models.AsyncModel, *, content_type: str = "applicati """ @overload - def with_async(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_async(self, body: _types.AsyncModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_async. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.AsyncModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1583,12 +1583,12 @@ def with_async(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_async( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.AsyncModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.AsyncModel, _types.AsyncModel, IO[bytes]], **kwargs: Any ) -> None: """with_async. - :param body: Is one of the following types: AsyncModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.AsyncModel or JSON or IO[bytes] + :param body: Is either a AsyncModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.AsyncModel or ~specialwords.types.AsyncModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1654,11 +1654,11 @@ def with_await(self, body: _models.AwaitModel, *, content_type: str = "applicati """ @overload - def with_await(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_await(self, body: _types.AwaitModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_await. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.AwaitModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1683,12 +1683,12 @@ def with_await(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_await( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.AwaitModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.AwaitModel, _types.AwaitModel, IO[bytes]], **kwargs: Any ) -> None: """with_await. - :param body: Is one of the following types: AwaitModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.AwaitModel or JSON or IO[bytes] + :param body: Is either a AwaitModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.AwaitModel or ~specialwords.types.AwaitModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1754,11 +1754,11 @@ def with_break(self, body: _models.BreakModel, *, content_type: str = "applicati """ @overload - def with_break(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_break(self, body: _types.BreakModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_break. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.BreakModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1783,12 +1783,12 @@ def with_break(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_break( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BreakModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BreakModel, _types.BreakModel, IO[bytes]], **kwargs: Any ) -> None: """with_break. - :param body: Is one of the following types: BreakModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.BreakModel or JSON or IO[bytes] + :param body: Is either a BreakModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.BreakModel or ~specialwords.types.BreakModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1854,11 +1854,11 @@ def with_class(self, body: _models.ClassModel, *, content_type: str = "applicati """ @overload - def with_class(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_class(self, body: _types.ClassModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_class. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ClassModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1883,12 +1883,12 @@ def with_class(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_class( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ClassModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ClassModel, _types.ClassModel, IO[bytes]], **kwargs: Any ) -> None: """with_class. - :param body: Is one of the following types: ClassModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ClassModel or JSON or IO[bytes] + :param body: Is either a ClassModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ClassModel or ~specialwords.types.ClassModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1956,11 +1956,13 @@ def with_constructor( """ @overload - def with_constructor(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_constructor( + self, body: _types.Constructor, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_constructor. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.Constructor :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1985,12 +1987,12 @@ def with_constructor(self, body: IO[bytes], *, content_type: str = "application/ @distributed_trace def with_constructor( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.Constructor, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.Constructor, _types.Constructor, IO[bytes]], **kwargs: Any ) -> None: """with_constructor. - :param body: Is one of the following types: Constructor, JSON, IO[bytes] Required. - :type body: ~specialwords.models.Constructor or JSON or IO[bytes] + :param body: Is either a Constructor type or a IO[bytes] type. Required. + :type body: ~specialwords.models.Constructor or ~specialwords.types.Constructor or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2058,11 +2060,13 @@ def with_continue( """ @overload - def with_continue(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_continue( + self, body: _types.ContinueModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_continue. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ContinueModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2087,12 +2091,13 @@ def with_continue(self, body: IO[bytes], *, content_type: str = "application/jso @distributed_trace def with_continue( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ContinueModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ContinueModel, _types.ContinueModel, IO[bytes]], **kwargs: Any ) -> None: """with_continue. - :param body: Is one of the following types: ContinueModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ContinueModel or JSON or IO[bytes] + :param body: Is either a ContinueModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ContinueModel or ~specialwords.types.ContinueModel or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2158,11 +2163,11 @@ def with_def(self, body: _models.DefModel, *, content_type: str = "application/j """ @overload - def with_def(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_def(self, body: _types.DefModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_def. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.DefModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2187,12 +2192,12 @@ def with_def(self, body: IO[bytes], *, content_type: str = "application/json", * @distributed_trace def with_def( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DefModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DefModel, _types.DefModel, IO[bytes]], **kwargs: Any ) -> None: """with_def. - :param body: Is one of the following types: DefModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.DefModel or JSON or IO[bytes] + :param body: Is either a DefModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.DefModel or ~specialwords.types.DefModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2258,11 +2263,11 @@ def with_del(self, body: _models.DelModel, *, content_type: str = "application/j """ @overload - def with_del(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_del(self, body: _types.DelModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_del. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.DelModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2287,12 +2292,12 @@ def with_del(self, body: IO[bytes], *, content_type: str = "application/json", * @distributed_trace def with_del( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DelModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DelModel, _types.DelModel, IO[bytes]], **kwargs: Any ) -> None: """with_del. - :param body: Is one of the following types: DelModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.DelModel or JSON or IO[bytes] + :param body: Is either a DelModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.DelModel or ~specialwords.types.DelModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2358,11 +2363,11 @@ def with_elif(self, body: _models.ElifModel, *, content_type: str = "application """ @overload - def with_elif(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_elif(self, body: _types.ElifModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_elif. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ElifModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2387,12 +2392,12 @@ def with_elif(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_elif( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ElifModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ElifModel, _types.ElifModel, IO[bytes]], **kwargs: Any ) -> None: """with_elif. - :param body: Is one of the following types: ElifModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ElifModel or JSON or IO[bytes] + :param body: Is either a ElifModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ElifModel or ~specialwords.types.ElifModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2458,11 +2463,11 @@ def with_else(self, body: _models.ElseModel, *, content_type: str = "application """ @overload - def with_else(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_else(self, body: _types.ElseModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_else. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ElseModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2487,12 +2492,12 @@ def with_else(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_else( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ElseModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ElseModel, _types.ElseModel, IO[bytes]], **kwargs: Any ) -> None: """with_else. - :param body: Is one of the following types: ElseModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ElseModel or JSON or IO[bytes] + :param body: Is either a ElseModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ElseModel or ~specialwords.types.ElseModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2558,11 +2563,11 @@ def with_except(self, body: _models.ExceptModel, *, content_type: str = "applica """ @overload - def with_except(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_except(self, body: _types.ExceptModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_except. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ExceptModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2587,12 +2592,12 @@ def with_except(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def with_except( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExceptModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ExceptModel, _types.ExceptModel, IO[bytes]], **kwargs: Any ) -> None: """with_except. - :param body: Is one of the following types: ExceptModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ExceptModel or JSON or IO[bytes] + :param body: Is either a ExceptModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ExceptModel or ~specialwords.types.ExceptModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2658,11 +2663,11 @@ def with_exec(self, body: _models.ExecModel, *, content_type: str = "application """ @overload - def with_exec(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_exec(self, body: _types.ExecModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_exec. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ExecModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2687,12 +2692,12 @@ def with_exec(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_exec( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExecModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ExecModel, _types.ExecModel, IO[bytes]], **kwargs: Any ) -> None: """with_exec. - :param body: Is one of the following types: ExecModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ExecModel or JSON or IO[bytes] + :param body: Is either a ExecModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ExecModel or ~specialwords.types.ExecModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2760,11 +2765,11 @@ def with_finally( """ @overload - def with_finally(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_finally(self, body: _types.FinallyModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_finally. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.FinallyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2789,12 +2794,12 @@ def with_finally(self, body: IO[bytes], *, content_type: str = "application/json @distributed_trace def with_finally( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FinallyModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.FinallyModel, _types.FinallyModel, IO[bytes]], **kwargs: Any ) -> None: """with_finally. - :param body: Is one of the following types: FinallyModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.FinallyModel or JSON or IO[bytes] + :param body: Is either a FinallyModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.FinallyModel or ~specialwords.types.FinallyModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2860,11 +2865,11 @@ def with_for(self, body: _models.ForModel, *, content_type: str = "application/j """ @overload - def with_for(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_for(self, body: _types.ForModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_for. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ForModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2889,12 +2894,12 @@ def with_for(self, body: IO[bytes], *, content_type: str = "application/json", * @distributed_trace def with_for( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ForModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ForModel, _types.ForModel, IO[bytes]], **kwargs: Any ) -> None: """with_for. - :param body: Is one of the following types: ForModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ForModel or JSON or IO[bytes] + :param body: Is either a ForModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ForModel or ~specialwords.types.ForModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2960,11 +2965,11 @@ def with_from(self, body: _models.FromModel, *, content_type: str = "application """ @overload - def with_from(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_from(self, body: _types.FromModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_from. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.FromModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2989,12 +2994,12 @@ def with_from(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_from( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FromModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.FromModel, _types.FromModel, IO[bytes]], **kwargs: Any ) -> None: """with_from. - :param body: Is one of the following types: FromModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.FromModel or JSON or IO[bytes] + :param body: Is either a FromModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.FromModel or ~specialwords.types.FromModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3060,11 +3065,11 @@ def with_global(self, body: _models.GlobalModel, *, content_type: str = "applica """ @overload - def with_global(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_global(self, body: _types.GlobalModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_global. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.GlobalModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3089,12 +3094,12 @@ def with_global(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def with_global( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.GlobalModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.GlobalModel, _types.GlobalModel, IO[bytes]], **kwargs: Any ) -> None: """with_global. - :param body: Is one of the following types: GlobalModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.GlobalModel or JSON or IO[bytes] + :param body: Is either a GlobalModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.GlobalModel or ~specialwords.types.GlobalModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3160,11 +3165,11 @@ def with_if(self, body: _models.IfModel, *, content_type: str = "application/jso """ @overload - def with_if(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_if(self, body: _types.IfModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_if. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.IfModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3189,12 +3194,12 @@ def with_if(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def with_if( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IfModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.IfModel, _types.IfModel, IO[bytes]], **kwargs: Any ) -> None: """with_if. - :param body: Is one of the following types: IfModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.IfModel or JSON or IO[bytes] + :param body: Is either a IfModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.IfModel or ~specialwords.types.IfModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3260,11 +3265,11 @@ def with_import(self, body: _models.ImportModel, *, content_type: str = "applica """ @overload - def with_import(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_import(self, body: _types.ImportModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_import. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ImportModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3289,12 +3294,12 @@ def with_import(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def with_import( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ImportModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ImportModel, _types.ImportModel, IO[bytes]], **kwargs: Any ) -> None: """with_import. - :param body: Is one of the following types: ImportModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ImportModel or JSON or IO[bytes] + :param body: Is either a ImportModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ImportModel or ~specialwords.types.ImportModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3360,11 +3365,11 @@ def with_in(self, body: _models.InModel, *, content_type: str = "application/jso """ @overload - def with_in(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_in(self, body: _types.InModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_in. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.InModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3389,12 +3394,12 @@ def with_in(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def with_in( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.InModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.InModel, _types.InModel, IO[bytes]], **kwargs: Any ) -> None: """with_in. - :param body: Is one of the following types: InModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.InModel or JSON or IO[bytes] + :param body: Is either a InModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.InModel or ~specialwords.types.InModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3460,11 +3465,11 @@ def with_is(self, body: _models.IsModel, *, content_type: str = "application/jso """ @overload - def with_is(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_is(self, body: _types.IsModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_is. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.IsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3489,12 +3494,12 @@ def with_is(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def with_is( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.IsModel, _types.IsModel, IO[bytes]], **kwargs: Any ) -> None: """with_is. - :param body: Is one of the following types: IsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.IsModel or JSON or IO[bytes] + :param body: Is either a IsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.IsModel or ~specialwords.types.IsModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3560,11 +3565,11 @@ def with_lambda(self, body: _models.LambdaModel, *, content_type: str = "applica """ @overload - def with_lambda(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_lambda(self, body: _types.LambdaModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_lambda. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.LambdaModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3589,12 +3594,12 @@ def with_lambda(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def with_lambda( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.LambdaModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.LambdaModel, _types.LambdaModel, IO[bytes]], **kwargs: Any ) -> None: """with_lambda. - :param body: Is one of the following types: LambdaModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.LambdaModel or JSON or IO[bytes] + :param body: Is either a LambdaModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.LambdaModel or ~specialwords.types.LambdaModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3660,11 +3665,11 @@ def with_not(self, body: _models.NotModel, *, content_type: str = "application/j """ @overload - def with_not(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_not(self, body: _types.NotModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_not. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.NotModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3689,12 +3694,12 @@ def with_not(self, body: IO[bytes], *, content_type: str = "application/json", * @distributed_trace def with_not( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.NotModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.NotModel, _types.NotModel, IO[bytes]], **kwargs: Any ) -> None: """with_not. - :param body: Is one of the following types: NotModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.NotModel or JSON or IO[bytes] + :param body: Is either a NotModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.NotModel or ~specialwords.types.NotModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3760,11 +3765,11 @@ def with_or(self, body: _models.OrModel, *, content_type: str = "application/jso """ @overload - def with_or(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_or(self, body: _types.OrModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_or. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.OrModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3789,12 +3794,12 @@ def with_or(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def with_or( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.OrModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.OrModel, _types.OrModel, IO[bytes]], **kwargs: Any ) -> None: """with_or. - :param body: Is one of the following types: OrModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.OrModel or JSON or IO[bytes] + :param body: Is either a OrModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.OrModel or ~specialwords.types.OrModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3860,11 +3865,11 @@ def with_pass(self, body: _models.PassModel, *, content_type: str = "application """ @overload - def with_pass(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_pass(self, body: _types.PassModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_pass. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.PassModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3889,12 +3894,12 @@ def with_pass(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_pass( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PassModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.PassModel, _types.PassModel, IO[bytes]], **kwargs: Any ) -> None: """with_pass. - :param body: Is one of the following types: PassModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.PassModel or JSON or IO[bytes] + :param body: Is either a PassModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.PassModel or ~specialwords.types.PassModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3960,11 +3965,11 @@ def with_raise(self, body: _models.RaiseModel, *, content_type: str = "applicati """ @overload - def with_raise(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_raise(self, body: _types.RaiseModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_raise. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.RaiseModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3989,12 +3994,12 @@ def with_raise(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_raise( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.RaiseModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.RaiseModel, _types.RaiseModel, IO[bytes]], **kwargs: Any ) -> None: """with_raise. - :param body: Is one of the following types: RaiseModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.RaiseModel or JSON or IO[bytes] + :param body: Is either a RaiseModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.RaiseModel or ~specialwords.types.RaiseModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4060,11 +4065,11 @@ def with_return(self, body: _models.ReturnModel, *, content_type: str = "applica """ @overload - def with_return(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_return(self, body: _types.ReturnModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_return. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ReturnModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4089,12 +4094,12 @@ def with_return(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def with_return( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ReturnModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ReturnModel, _types.ReturnModel, IO[bytes]], **kwargs: Any ) -> None: """with_return. - :param body: Is one of the following types: ReturnModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ReturnModel or JSON or IO[bytes] + :param body: Is either a ReturnModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ReturnModel or ~specialwords.types.ReturnModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4160,11 +4165,11 @@ def with_try(self, body: _models.TryModel, *, content_type: str = "application/j """ @overload - def with_try(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_try(self, body: _types.TryModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_try. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.TryModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4189,12 +4194,12 @@ def with_try(self, body: IO[bytes], *, content_type: str = "application/json", * @distributed_trace def with_try( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.TryModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.TryModel, _types.TryModel, IO[bytes]], **kwargs: Any ) -> None: """with_try. - :param body: Is one of the following types: TryModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.TryModel or JSON or IO[bytes] + :param body: Is either a TryModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.TryModel or ~specialwords.types.TryModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4260,11 +4265,11 @@ def with_while(self, body: _models.WhileModel, *, content_type: str = "applicati """ @overload - def with_while(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_while(self, body: _types.WhileModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_while. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.WhileModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4289,12 +4294,12 @@ def with_while(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_while( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.WhileModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.WhileModel, _types.WhileModel, IO[bytes]], **kwargs: Any ) -> None: """with_while. - :param body: Is one of the following types: WhileModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.WhileModel or JSON or IO[bytes] + :param body: Is either a WhileModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.WhileModel or ~specialwords.types.WhileModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4360,11 +4365,11 @@ def with_with(self, body: _models.WithModel, *, content_type: str = "application """ @overload - def with_with(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_with(self, body: _types.WithModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_with. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.WithModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4389,12 +4394,12 @@ def with_with(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_with( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.WithModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.WithModel, _types.WithModel, IO[bytes]], **kwargs: Any ) -> None: """with_with. - :param body: Is one of the following types: WithModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.WithModel or JSON or IO[bytes] + :param body: Is either a WithModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.WithModel or ~specialwords.types.WithModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4460,11 +4465,11 @@ def with_yield(self, body: _models.YieldModel, *, content_type: str = "applicati """ @overload - def with_yield(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_yield(self, body: _types.YieldModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_yield. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.YieldModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4489,12 +4494,12 @@ def with_yield(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_yield( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.YieldModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.YieldModel, _types.YieldModel, IO[bytes]], **kwargs: Any ) -> None: """with_yield. - :param body: Is one of the following types: YieldModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.YieldModel or JSON or IO[bytes] + :param body: Is either a YieldModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.YieldModel or ~specialwords.types.YieldModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4580,11 +4585,11 @@ def same_as_model( """ @overload - def same_as_model(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def same_as_model(self, body: _types.SameAsModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """same_as_model. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.SameAsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4609,12 +4614,12 @@ def same_as_model(self, body: IO[bytes], *, content_type: str = "application/jso @distributed_trace def same_as_model( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SameAsModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SameAsModel, _types.SameAsModel, IO[bytes]], **kwargs: Any ) -> None: """same_as_model. - :param body: Is one of the following types: SameAsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.SameAsModel or JSON or IO[bytes] + :param body: Is either a SameAsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.SameAsModel or ~specialwords.types.SameAsModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4680,11 +4685,11 @@ def dict_methods(self, body: _models.DictMethods, *, content_type: str = "applic """ @overload - def dict_methods(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def dict_methods(self, body: _types.DictMethods, *, content_type: str = "application/json", **kwargs: Any) -> None: """dict_methods. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.DictMethods :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4709,12 +4714,12 @@ def dict_methods(self, body: IO[bytes], *, content_type: str = "application/json @distributed_trace def dict_methods( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DictMethods, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DictMethods, _types.DictMethods, IO[bytes]], **kwargs: Any ) -> None: """dict_methods. - :param body: Is one of the following types: DictMethods, JSON, IO[bytes] Required. - :type body: ~specialwords.models.DictMethods or JSON or IO[bytes] + :param body: Is either a DictMethods type or a IO[bytes] type. Required. + :type body: ~specialwords.models.DictMethods or ~specialwords.types.DictMethods or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4780,11 +4785,11 @@ def with_list(self, body: _models.ModelWithList, *, content_type: str = "applica """ @overload - def with_list(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_list(self, body: _types.ModelWithList, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_list. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.ModelWithList :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4809,12 +4814,13 @@ def with_list(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_list( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ModelWithList, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ModelWithList, _types.ModelWithList, IO[bytes]], **kwargs: Any ) -> None: """with_list. - :param body: Is one of the following types: ModelWithList, JSON, IO[bytes] Required. - :type body: ~specialwords.models.ModelWithList or JSON or IO[bytes] + :param body: Is either a ModelWithList type or a IO[bytes] type. Required. + :type body: ~specialwords.models.ModelWithList or ~specialwords.types.ModelWithList or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4898,11 +4904,13 @@ def with_items(self, *, items: list[str], content_type: str = "application/json" """ @overload - def with_items(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_items( + self, body: _types.WithItemsRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_items. :param body: Required. - :type body: JSON + :type body: ~specialwords.types.WithItemsRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4927,12 +4935,16 @@ def with_items(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace def with_items( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, items: list[str] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.WithItemsRequest, IO[bytes]] = _Unset, + *, + items: list[str] = _Unset, + **kwargs: Any, ) -> None: """with_items. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, WithItemsRequest, IO[bytes] Required. + :type body: JSON or ~specialwords.types.WithItemsRequest or IO[bytes] :keyword items: Required. :paramtype items: list[str] :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/types.py index 7575fd0bb676..ba883aff0589 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/special-words/specialwords/types.py @@ -439,3 +439,14 @@ class YieldModel(TypedDict, total=False): name: Required[str] """Required.""" + + +class WithItemsRequest(TypedDict, total=False): + """WithItemsRequest. + + :ivar items_property: Required. + :vartype items_property: list[str] + """ + + items: Required[list[str]] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/pyproject.toml index d97a520074df..aee588fed98c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/operations/_operations.py index b783a5ade042..298ea72a1919 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/operations/_operations.py @@ -24,7 +24,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -137,11 +137,13 @@ async def bullet_points_model( """ @overload - async def bullet_points_model(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def bullet_points_model( + self, body: _types.BulletPointsModelRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """bullet_points_model. :param body: Required. - :type body: JSON + :type body: ~specs.documentation.types.BulletPointsModelRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -168,12 +170,16 @@ async def bullet_points_model( @distributed_trace_async async def bullet_points_model( - self, body: Union[JSON, IO[bytes]] = _Unset, *, input: _models.BulletPointsModel = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.BulletPointsModelRequest, IO[bytes]] = _Unset, + *, + input: _models.BulletPointsModel = _Unset, + **kwargs: Any ) -> None: """bullet_points_model. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BulletPointsModelRequest, IO[bytes] Required. + :type body: JSON or ~specs.documentation.types.BulletPointsModelRequest or IO[bytes] :keyword input: Required. :paramtype input: ~specs.documentation.models.BulletPointsModel :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/operations/_operations.py index 48f21f063890..ecf961c7f15e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/operations/_operations.py @@ -24,7 +24,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import DocumentationClientConfiguration from .._utils.model_base import SdkJSONEncoder from .._utils.serialization import Deserializer, Serializer @@ -181,11 +181,13 @@ def bullet_points_model( """ @overload - def bullet_points_model(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def bullet_points_model( + self, body: _types.BulletPointsModelRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """bullet_points_model. :param body: Required. - :type body: JSON + :type body: ~specs.documentation.types.BulletPointsModelRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -210,12 +212,16 @@ def bullet_points_model(self, body: IO[bytes], *, content_type: str = "applicati @distributed_trace def bullet_points_model( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, input: _models.BulletPointsModel = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.BulletPointsModelRequest, IO[bytes]] = _Unset, + *, + input: _models.BulletPointsModel = _Unset, + **kwargs: Any ) -> None: """bullet_points_model. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BulletPointsModelRequest, IO[bytes] Required. + :type body: JSON or ~specs.documentation.types.BulletPointsModelRequest or IO[bytes] :keyword input: Required. :paramtype input: ~specs.documentation.models.BulletPointsModel :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/types.py index 8c166362b772..f4dcf39b4a85 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/specs-documentation/specs/documentation/types.py @@ -46,7 +46,7 @@ class BulletPointsModel(TypedDict, total=False): both bold and italic formatting and is long enough to test the wrapping behavior in such cases. * **Bold bullet point** * *Italic bullet point*. Required. Known values are: "Simple", "Bold", and "Italic". - :vartype prop: str or ~specs.documentation.models.BulletPointsEnum + :vartype prop: Union[str, "BulletPointsEnum"] """ prop: Required[Union[str, "BulletPointsEnum"]] @@ -64,3 +64,14 @@ class BulletPointsModel(TypedDict, total=False): both bold and italic formatting and is long enough to test the wrapping behavior in such cases. * **Bold bullet point** * *Italic bullet point*. Required. Known values are: \"Simple\", \"Bold\", and \"Italic\".""" + + +class BulletPointsModelRequest(TypedDict, total=False): + """BulletPointsModelRequest. + + :ivar input: Required. + :vartype input: "BulletPointsModel" + """ + + input: Required["BulletPointsModel"] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/pyproject.toml index 600f163f2056..d5630e988824 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/types.py deleted file mode 100644 index c9304917a17c..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/streaming-jsonl/streaming/jsonl/basic/types.py +++ /dev/null @@ -1,20 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing_extensions import Required, TypedDict - - -class Info(TypedDict, total=False): - """Info. - - :ivar desc: Required. - :vartype desc: str - """ - - desc: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/pyproject.toml index 2b248546f05c..54f626bda3d5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/operations/_operations.py index 4fd28357785a..a09c17bdb7ab 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/operations/_operations.py @@ -28,7 +28,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -65,7 +65,6 @@ T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] class Int32ValueOperations: @@ -1435,11 +1434,13 @@ async def put( """ @overload - async def put(self, body: list[JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: list[_types.InnerModel], *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put. :param body: Required. - :type body: list[JSON] + :type body: list[~typetest.array.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1463,11 +1464,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[list[_models.InnerModel], list[JSON], IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[list[_models.InnerModel], list[_types.InnerModel], IO[bytes]], **kwargs: Any + ) -> None: """put. - :param body: Is one of the following types: [InnerModel], [JSON], IO[bytes] Required. - :type body: list[~typetest.array.models.InnerModel] or list[JSON] or IO[bytes] + :param body: Is either a [InnerModel] type or a IO[bytes] type. Required. + :type body: list[~typetest.array.models.InnerModel] or list[~typetest.array.types.InnerModel] + or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2246,11 +2250,13 @@ async def put( """ @overload - async def put(self, body: list[JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: list[_types.InnerModel], *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put. :param body: Required. - :type body: list[JSON] + :type body: list[~typetest.array.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2274,11 +2280,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[list[_models.InnerModel], list[JSON], IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[list[_models.InnerModel], list[_types.InnerModel], IO[bytes]], **kwargs: Any + ) -> None: """put. - :param body: Is one of the following types: [InnerModel], [JSON], IO[bytes] Required. - :type body: list[~typetest.array.models.InnerModel] or list[JSON] or IO[bytes] + :param body: Is either a [InnerModel] type or a IO[bytes] type. Required. + :type body: list[~typetest.array.models.InnerModel] or list[~typetest.array.types.InnerModel] + or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/operations/_operations.py index aa7aa0208808..dda72725a2a5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/operations/_operations.py @@ -28,14 +28,13 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import ArrayClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -1810,11 +1809,11 @@ def put(self, body: list[_models.InnerModel], *, content_type: str = "applicatio """ @overload - def put(self, body: list[JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: list[_types.InnerModel], *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param body: Required. - :type body: list[JSON] + :type body: list[~typetest.array.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1839,12 +1838,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[list[_models.InnerModel], list[JSON], IO[bytes]], **kwargs: Any + self, body: Union[list[_models.InnerModel], list[_types.InnerModel], IO[bytes]], **kwargs: Any ) -> None: """put. - :param body: Is one of the following types: [InnerModel], [JSON], IO[bytes] Required. - :type body: list[~typetest.array.models.InnerModel] or list[JSON] or IO[bytes] + :param body: Is either a [InnerModel] type or a IO[bytes] type. Required. + :type body: list[~typetest.array.models.InnerModel] or list[~typetest.array.types.InnerModel] + or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2629,11 +2629,11 @@ def put(self, body: list[_models.InnerModel], *, content_type: str = "applicatio """ @overload - def put(self, body: list[JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: list[_types.InnerModel], *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param body: Required. - :type body: list[JSON] + :type body: list[~typetest.array.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2658,12 +2658,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[list[_models.InnerModel], list[JSON], IO[bytes]], **kwargs: Any + self, body: Union[list[_models.InnerModel], list[_types.InnerModel], IO[bytes]], **kwargs: Any ) -> None: """put. - :param body: Is one of the following types: [InnerModel], [JSON], IO[bytes] Required. - :type body: list[~typetest.array.models.InnerModel] or list[JSON] or IO[bytes] + :param body: Is either a [InnerModel] type or a IO[bytes] type. Required. + :type body: list[~typetest.array.models.InnerModel] or list[~typetest.array.types.InnerModel] + or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/types.py index fe2094055f08..eb2d4c53c5a6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-array/typetest/array/types.py @@ -15,7 +15,7 @@ class InnerModel(TypedDict, total=False): :ivar property: Required string property. Required. :vartype property: str :ivar children: - :vartype children: list[~typetest.array.models.InnerModel] + :vartype children: list["InnerModel"] """ property: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/pyproject.toml index 74724aa7abc1..34934ceb311c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/operations/_operations.py index 7cf7593db1e4..ca88cbdc18da 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/operations/_operations.py @@ -28,7 +28,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -59,7 +59,6 @@ T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] class Int32ValueOperations: @@ -1429,11 +1428,13 @@ async def put( """ @overload - async def put(self, body: dict[str, JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: dict[str, _types.InnerModel], *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put. :param body: Required. - :type body: dict[str, JSON] + :type body: dict[str, ~typetest.dictionary.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1457,11 +1458,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[dict[str, _models.InnerModel], dict[str, JSON], IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[dict[str, _models.InnerModel], dict[str, _types.InnerModel], IO[bytes]], **kwargs: Any + ) -> None: """put. - :param body: Is one of the following types: {str: InnerModel}, {str: JSON}, IO[bytes] Required. - :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, JSON] or IO[bytes] + :param body: Is either a {str: InnerModel} type or a IO[bytes] type. Required. + :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, + ~typetest.dictionary.types.InnerModel] or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1604,11 +1608,13 @@ async def put( """ @overload - async def put(self, body: dict[str, JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: dict[str, _types.InnerModel], *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put. :param body: Required. - :type body: dict[str, JSON] + :type body: dict[str, ~typetest.dictionary.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1632,11 +1638,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[dict[str, _models.InnerModel], dict[str, JSON], IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[dict[str, _models.InnerModel], dict[str, _types.InnerModel], IO[bytes]], **kwargs: Any + ) -> None: """put. - :param body: Is one of the following types: {str: InnerModel}, {str: JSON}, IO[bytes] Required. - :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, JSON] or IO[bytes] + :param body: Is either a {str: InnerModel} type or a IO[bytes] type. Required. + :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, + ~typetest.dictionary.types.InnerModel] or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/operations/_operations.py index 0ee8e2c8de5c..4004369450e7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/operations/_operations.py @@ -28,14 +28,13 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import DictionaryClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -1730,11 +1729,11 @@ def put( """ @overload - def put(self, body: dict[str, JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: dict[str, _types.InnerModel], *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param body: Required. - :type body: dict[str, JSON] + :type body: dict[str, ~typetest.dictionary.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1759,12 +1758,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[dict[str, _models.InnerModel], dict[str, JSON], IO[bytes]], **kwargs: Any + self, body: Union[dict[str, _models.InnerModel], dict[str, _types.InnerModel], IO[bytes]], **kwargs: Any ) -> None: """put. - :param body: Is one of the following types: {str: InnerModel}, {str: JSON}, IO[bytes] Required. - :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, JSON] or IO[bytes] + :param body: Is either a {str: InnerModel} type or a IO[bytes] type. Required. + :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, + ~typetest.dictionary.types.InnerModel] or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1907,11 +1907,11 @@ def put( """ @overload - def put(self, body: dict[str, JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: dict[str, _types.InnerModel], *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param body: Required. - :type body: dict[str, JSON] + :type body: dict[str, ~typetest.dictionary.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1936,12 +1936,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[dict[str, _models.InnerModel], dict[str, JSON], IO[bytes]], **kwargs: Any + self, body: Union[dict[str, _models.InnerModel], dict[str, _types.InnerModel], IO[bytes]], **kwargs: Any ) -> None: """put. - :param body: Is one of the following types: {str: InnerModel}, {str: JSON}, IO[bytes] Required. - :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, JSON] or IO[bytes] + :param body: Is either a {str: InnerModel} type or a IO[bytes] type. Required. + :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, + ~typetest.dictionary.types.InnerModel] or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/types.py index 58e1c2ce9402..a95f39d59863 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-dictionary/typetest/dictionary/types.py @@ -15,7 +15,7 @@ class InnerModel(TypedDict, total=False): :ivar property: Required string property. Required. :vartype property: str :ivar children: - :vartype children: dict[str, ~typetest.dictionary.models.InnerModel] + :vartype children: dict[str, "InnerModel"] """ property: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/pyproject.toml index a5ca63c17048..995aba6912ae 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_types.py deleted file mode 100644 index 5fd92d86ad7e..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_types.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import TYPE_CHECKING, Union - -if TYPE_CHECKING: - from . import models as _models -PetWithEnvelope = Union["_models.Cat", "_models.Dog"] -PetWithCustomNames = Union["_models.Cat", "_models.Dog"] -PetInline = Union["_models.Cat", "_models.Dog"] -PetInlineWithCustomDiscriminator = Union["_models.Cat", "_models.Dog"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_operations.py index 26f5dc5baf65..d8759bae8148 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_operations.py @@ -41,7 +41,7 @@ from .._configuration import DiscriminatedClientConfiguration if TYPE_CHECKING: - from ... import _types + from ... import _unions T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -130,7 +130,7 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async - async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetInline": + async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_unions.PetInline": """get. :keyword kind: Default value is None. @@ -150,7 +150,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetInline"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInline"] = kwargs.pop("cls", None) _request = build_no_envelope_default_get_request( kind=kind, @@ -182,7 +182,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInline", response.json()) + deserialized = _deserialize("_unions.PetInline", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -192,7 +192,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet @overload async def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInline": + ) -> "_unions.PetInline": """put. :param input: Required. @@ -208,7 +208,7 @@ async def put( @overload async def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInline": + ) -> "_unions.PetInline": """put. :param input: Required. @@ -222,7 +222,7 @@ async def put( """ @distributed_trace_async - async def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInline": + async def put(self, input: "_unions.PetInline", **kwargs: Any) -> "_unions.PetInline": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -243,7 +243,7 @@ async def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInli _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetInline"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInline"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -279,7 +279,7 @@ async def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInli if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInline", response.json()) + deserialized = _deserialize("_unions.PetInline", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -305,7 +305,7 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async - async def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.PetInlineWithCustomDiscriminator": + async def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_unions.PetInlineWithCustomDiscriminator": """get. :keyword type: Default value is None. @@ -325,7 +325,7 @@ async def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.Pet _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) _request = build_no_envelope_custom_discriminator_get_request( type=type, @@ -357,7 +357,7 @@ async def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.Pet if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInlineWithCustomDiscriminator", response.json()) + deserialized = _deserialize("_unions.PetInlineWithCustomDiscriminator", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -367,7 +367,7 @@ async def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.Pet @overload async def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Required. @@ -383,7 +383,7 @@ async def put( @overload async def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Required. @@ -398,8 +398,8 @@ async def put( @distributed_trace_async async def put( - self, input: "_types.PetInlineWithCustomDiscriminator", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + self, input: "_unions.PetInlineWithCustomDiscriminator", **kwargs: Any + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -420,7 +420,7 @@ async def put( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -456,7 +456,7 @@ async def put( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInlineWithCustomDiscriminator", response.json()) + deserialized = _deserialize("_unions.PetInlineWithCustomDiscriminator", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -482,7 +482,7 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async - async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetWithEnvelope": + async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_unions.PetWithEnvelope": """get. :keyword kind: Default value is None. @@ -502,7 +502,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetWithEnvelope"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithEnvelope"] = kwargs.pop("cls", None) _request = build_envelope_object_default_get_request( kind=kind, @@ -534,7 +534,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithEnvelope", response.json()) + deserialized = _deserialize("_unions.PetWithEnvelope", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -544,7 +544,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet @overload async def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithEnvelope": + ) -> "_unions.PetWithEnvelope": """put. :param input: Required. @@ -560,7 +560,7 @@ async def put( @overload async def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithEnvelope": + ) -> "_unions.PetWithEnvelope": """put. :param input: Required. @@ -574,7 +574,7 @@ async def put( """ @distributed_trace_async - async def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.PetWithEnvelope": + async def put(self, input: "_unions.PetWithEnvelope", **kwargs: Any) -> "_unions.PetWithEnvelope": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -595,7 +595,7 @@ async def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.P _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetWithEnvelope"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithEnvelope"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -631,7 +631,7 @@ async def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.P if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithEnvelope", response.json()) + deserialized = _deserialize("_unions.PetWithEnvelope", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -657,7 +657,7 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async - async def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types.PetWithCustomNames": + async def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_unions.PetWithCustomNames": """get. :keyword pet_type: Default value is None. @@ -677,7 +677,7 @@ async def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetWithCustomNames"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithCustomNames"] = kwargs.pop("cls", None) _request = build_envelope_object_custom_properties_get_request( pet_type=pet_type, @@ -709,7 +709,7 @@ async def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithCustomNames", response.json()) + deserialized = _deserialize("_unions.PetWithCustomNames", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -719,7 +719,7 @@ async def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types @overload async def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithCustomNames": + ) -> "_unions.PetWithCustomNames": """put. :param input: Required. @@ -735,7 +735,7 @@ async def put( @overload async def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithCustomNames": + ) -> "_unions.PetWithCustomNames": """put. :param input: Required. @@ -749,7 +749,7 @@ async def put( """ @distributed_trace_async - async def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_types.PetWithCustomNames": + async def put(self, input: "_unions.PetWithCustomNames", **kwargs: Any) -> "_unions.PetWithCustomNames": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -770,7 +770,7 @@ async def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_type _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetWithCustomNames"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithCustomNames"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -806,7 +806,7 @@ async def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_type if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithCustomNames", response.json()) + deserialized = _deserialize("_unions.PetWithCustomNames", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/operations/_operations.py index b7af499fbc25..33215e0ef5b4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/operations/_operations.py @@ -31,7 +31,7 @@ from .._utils.serialization import Deserializer, Serializer if TYPE_CHECKING: - from .. import _types + from .. import _unions T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -273,7 +273,7 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetInline": + def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_unions.PetInline": """get. :keyword kind: Default value is None. @@ -293,7 +293,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetInline _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetInline"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInline"] = kwargs.pop("cls", None) _request = build_no_envelope_default_get_request( kind=kind, @@ -325,7 +325,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetInline if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInline", response.json()) + deserialized = _deserialize("_unions.PetInline", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -333,7 +333,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetInline return deserialized # type: ignore @overload - def put(self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any) -> "_types.PetInline": + def put(self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any) -> "_unions.PetInline": """put. :param input: Required. @@ -347,7 +347,7 @@ def put(self, input: _models.Cat, *, content_type: str = "application/json", **k """ @overload - def put(self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any) -> "_types.PetInline": + def put(self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any) -> "_unions.PetInline": """put. :param input: Required. @@ -361,7 +361,7 @@ def put(self, input: _models.Dog, *, content_type: str = "application/json", **k """ @distributed_trace - def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInline": + def put(self, input: "_unions.PetInline", **kwargs: Any) -> "_unions.PetInline": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -382,7 +382,7 @@ def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInline": _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetInline"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInline"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -418,7 +418,7 @@ def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInline": if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInline", response.json()) + deserialized = _deserialize("_unions.PetInline", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -444,7 +444,7 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.PetInlineWithCustomDiscriminator": + def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_unions.PetInlineWithCustomDiscriminator": """get. :keyword type: Default value is None. @@ -464,7 +464,7 @@ def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.PetInline _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) _request = build_no_envelope_custom_discriminator_get_request( type=type, @@ -496,7 +496,7 @@ def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.PetInline if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInlineWithCustomDiscriminator", response.json()) + deserialized = _deserialize("_unions.PetInlineWithCustomDiscriminator", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -506,7 +506,7 @@ def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.PetInline @overload def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Required. @@ -522,7 +522,7 @@ def put( @overload def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Required. @@ -537,8 +537,8 @@ def put( @distributed_trace def put( - self, input: "_types.PetInlineWithCustomDiscriminator", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + self, input: "_unions.PetInlineWithCustomDiscriminator", **kwargs: Any + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -559,7 +559,7 @@ def put( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -595,7 +595,7 @@ def put( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInlineWithCustomDiscriminator", response.json()) + deserialized = _deserialize("_unions.PetInlineWithCustomDiscriminator", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -621,7 +621,7 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetWithEnvelope": + def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_unions.PetWithEnvelope": """get. :keyword kind: Default value is None. @@ -641,7 +641,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetWithEn _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetWithEnvelope"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithEnvelope"] = kwargs.pop("cls", None) _request = build_envelope_object_default_get_request( kind=kind, @@ -673,7 +673,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetWithEn if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithEnvelope", response.json()) + deserialized = _deserialize("_unions.PetWithEnvelope", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -683,7 +683,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetWithEn @overload def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithEnvelope": + ) -> "_unions.PetWithEnvelope": """put. :param input: Required. @@ -699,7 +699,7 @@ def put( @overload def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithEnvelope": + ) -> "_unions.PetWithEnvelope": """put. :param input: Required. @@ -713,7 +713,7 @@ def put( """ @distributed_trace - def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.PetWithEnvelope": + def put(self, input: "_unions.PetWithEnvelope", **kwargs: Any) -> "_unions.PetWithEnvelope": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -734,7 +734,7 @@ def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.PetWith _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetWithEnvelope"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithEnvelope"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -770,7 +770,7 @@ def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.PetWith if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithEnvelope", response.json()) + deserialized = _deserialize("_unions.PetWithEnvelope", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -796,7 +796,7 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types.PetWithCustomNames": + def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_unions.PetWithCustomNames": """get. :keyword pet_type: Default value is None. @@ -816,7 +816,7 @@ def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types.PetWi _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetWithCustomNames"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithCustomNames"] = kwargs.pop("cls", None) _request = build_envelope_object_custom_properties_get_request( pet_type=pet_type, @@ -848,7 +848,7 @@ def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types.PetWi if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithCustomNames", response.json()) + deserialized = _deserialize("_unions.PetWithCustomNames", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -858,7 +858,7 @@ def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types.PetWi @overload def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithCustomNames": + ) -> "_unions.PetWithCustomNames": """put. :param input: Required. @@ -874,7 +874,7 @@ def put( @overload def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithCustomNames": + ) -> "_unions.PetWithCustomNames": """put. :param input: Required. @@ -888,7 +888,7 @@ def put( """ @distributed_trace - def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_types.PetWithCustomNames": + def put(self, input: "_unions.PetWithCustomNames", **kwargs: Any) -> "_unions.PetWithCustomNames": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -909,7 +909,7 @@ def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_types.PetW _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetWithCustomNames"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithCustomNames"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -945,7 +945,7 @@ def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_types.PetW if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithCustomNames", response.json()) + deserialized = _deserialize("_unions.PetWithCustomNames", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/types.py deleted file mode 100644 index 0ab282f27792..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-discriminatedunion/typetest/discriminatedunion/types.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing_extensions import Required, TypedDict - - -class Cat(TypedDict, total=False): - """Cat. - - :ivar name: Required. - :vartype name: str - :ivar meow: Required. - :vartype meow: bool - """ - - name: Required[str] - """Required.""" - meow: Required[bool] - """Required.""" - - -class Dog(TypedDict, total=False): - """Dog. - - :ivar name: Required. - :vartype name: str - :ivar bark: Required. - :vartype bark: bool - """ - - name: Required[str] - """Required.""" - bark: Required[bool] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/pyproject.toml index 2909f0b2770c..40f19ebf608a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-extensible/typetest/enum/extensible/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/pyproject.toml index 51537f411aea..7eeef85c3a93 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-enum-fixed/typetest/enum/fixed/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/pyproject.toml index 22800e8b57ae..0723ca57a7a2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_operations/_operations.py index e9521479cdb7..ca4374be31c0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import EmptyClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -102,11 +101,11 @@ def put_empty(self, input: _models.EmptyInput, *, content_type: str = "applicati """ @overload - def put_empty(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_empty(self, input: _types.EmptyInput, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_empty. :param input: Required. - :type input: JSON + :type input: ~typetest.model.empty.types.EmptyInput :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -131,12 +130,13 @@ def put_empty(self, input: IO[bytes], *, content_type: str = "application/json", @distributed_trace def put_empty( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.EmptyInput, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.EmptyInput, _types.EmptyInput, IO[bytes]], **kwargs: Any ) -> None: """put_empty. - :param input: Is one of the following types: EmptyInput, JSON, IO[bytes] Required. - :type input: ~typetest.model.empty.models.EmptyInput or JSON or IO[bytes] + :param input: Is either a EmptyInput type or a IO[bytes] type. Required. + :type input: ~typetest.model.empty.models.EmptyInput or ~typetest.model.empty.types.EmptyInput + or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -262,12 +262,12 @@ def post_round_trip_empty( @overload def post_round_trip_empty( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.EmptyInputOutput, *, content_type: str = "application/json", **kwargs: Any ) -> _models.EmptyInputOutput: """post_round_trip_empty. :param body: Required. - :type body: JSON + :type body: ~typetest.model.empty.types.EmptyInputOutput :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -294,12 +294,13 @@ def post_round_trip_empty( @distributed_trace def post_round_trip_empty( - self, body: Union[_models.EmptyInputOutput, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.EmptyInputOutput, _types.EmptyInputOutput, IO[bytes]], **kwargs: Any ) -> _models.EmptyInputOutput: """post_round_trip_empty. - :param body: Is one of the following types: EmptyInputOutput, JSON, IO[bytes] Required. - :type body: ~typetest.model.empty.models.EmptyInputOutput or JSON or IO[bytes] + :param body: Is either a EmptyInputOutput type or a IO[bytes] type. Required. + :type body: ~typetest.model.empty.models.EmptyInputOutput or + ~typetest.model.empty.types.EmptyInputOutput or IO[bytes] :return: EmptyInputOutput. The EmptyInputOutput is compatible with MutableMapping :rtype: ~typetest.model.empty.models.EmptyInputOutput :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_operations/_operations.py index 7d3b18b75ee2..893b7a59a19d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_empty_get_empty_request, build_empty_post_round_trip_empty_request, @@ -37,7 +37,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import EmptyClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -63,11 +62,13 @@ async def put_empty( """ @overload - async def put_empty(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_empty( + self, input: _types.EmptyInput, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_empty. :param input: Required. - :type input: JSON + :type input: ~typetest.model.empty.types.EmptyInput :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -91,11 +92,12 @@ async def put_empty(self, input: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def put_empty(self, input: Union[_models.EmptyInput, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_empty(self, input: Union[_models.EmptyInput, _types.EmptyInput, IO[bytes]], **kwargs: Any) -> None: """put_empty. - :param input: Is one of the following types: EmptyInput, JSON, IO[bytes] Required. - :type input: ~typetest.model.empty.models.EmptyInput or JSON or IO[bytes] + :param input: Is either a EmptyInput type or a IO[bytes] type. Required. + :type input: ~typetest.model.empty.models.EmptyInput or ~typetest.model.empty.types.EmptyInput + or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -221,12 +223,12 @@ async def post_round_trip_empty( @overload async def post_round_trip_empty( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.EmptyInputOutput, *, content_type: str = "application/json", **kwargs: Any ) -> _models.EmptyInputOutput: """post_round_trip_empty. :param body: Required. - :type body: JSON + :type body: ~typetest.model.empty.types.EmptyInputOutput :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -253,12 +255,13 @@ async def post_round_trip_empty( @distributed_trace_async async def post_round_trip_empty( - self, body: Union[_models.EmptyInputOutput, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.EmptyInputOutput, _types.EmptyInputOutput, IO[bytes]], **kwargs: Any ) -> _models.EmptyInputOutput: """post_round_trip_empty. - :param body: Is one of the following types: EmptyInputOutput, JSON, IO[bytes] Required. - :type body: ~typetest.model.empty.models.EmptyInputOutput or JSON or IO[bytes] + :param body: Is either a EmptyInputOutput type or a IO[bytes] type. Required. + :type body: ~typetest.model.empty.models.EmptyInputOutput or + ~typetest.model.empty.types.EmptyInputOutput or IO[bytes] :return: EmptyInputOutput. The EmptyInputOutput is compatible with MutableMapping :rtype: ~typetest.model.empty.models.EmptyInputOutput :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/types.py index 1ecc1c8a331c..695b50c067bb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-empty/typetest/model/empty/types.py @@ -15,7 +15,3 @@ class EmptyInput(TypedDict, total=False): class EmptyInputOutput(TypedDict, total=False): """Empty model used in both parameter and return type.""" - - -class EmptyOutput(TypedDict, total=False): - """Empty model used in operation return type.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/pyproject.toml index 7ce21d4aa112..b3914b0a6a65 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_operations.py index 126c0cda2f41..dfaa1d580020 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import EnumDiscriminatorClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -242,11 +241,11 @@ def put_extensible_model( """ @overload - def put_extensible_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_extensible_model(self, input: _types.Dog, *, content_type: str = "application/json", **kwargs: Any) -> None: """Send model with extensible enum discriminator type. :param input: Dog to create. Required. - :type input: JSON + :type input: ~typetest.model.enumdiscriminator.types.Dog :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -271,12 +270,13 @@ def put_extensible_model(self, input: IO[bytes], *, content_type: str = "applica @distributed_trace def put_extensible_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Dog, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Dog, _types.Dog, IO[bytes]], **kwargs: Any ) -> None: """Send model with extensible enum discriminator type. - :param input: Dog to create. Is one of the following types: Dog, JSON, IO[bytes] Required. - :type input: ~typetest.model.enumdiscriminator.models.Dog or JSON or IO[bytes] + :param input: Dog to create. Is either a Dog type or a IO[bytes] type. Required. + :type input: ~typetest.model.enumdiscriminator.models.Dog or + ~typetest.model.enumdiscriminator.types.Dog or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -513,11 +513,11 @@ def put_fixed_model(self, input: _models.Snake, *, content_type: str = "applicat """ @overload - def put_fixed_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_fixed_model(self, input: _types.Snake, *, content_type: str = "application/json", **kwargs: Any) -> None: """Send model with fixed enum discriminator type. :param input: Snake to create. Required. - :type input: JSON + :type input: ~typetest.model.enumdiscriminator.types.Snake :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -542,12 +542,13 @@ def put_fixed_model(self, input: IO[bytes], *, content_type: str = "application/ @distributed_trace def put_fixed_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Snake, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Snake, _types.Snake, IO[bytes]], **kwargs: Any ) -> None: """Send model with fixed enum discriminator type. - :param input: Snake to create. Is one of the following types: Snake, JSON, IO[bytes] Required. - :type input: ~typetest.model.enumdiscriminator.models.Snake or JSON or IO[bytes] + :param input: Snake to create. Is either a Snake type or a IO[bytes] type. Required. + :type input: ~typetest.model.enumdiscriminator.models.Snake or + ~typetest.model.enumdiscriminator.types.Snake or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_operations.py index 7de0ce9fbf98..1eaebc5016d9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_enum_discriminator_get_extensible_model_missing_discriminator_request, build_enum_discriminator_get_extensible_model_request, @@ -42,7 +42,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import EnumDiscriminatorClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -125,11 +124,13 @@ async def put_extensible_model( """ @overload - async def put_extensible_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_extensible_model( + self, input: _types.Dog, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Send model with extensible enum discriminator type. :param input: Dog to create. Required. - :type input: JSON + :type input: ~typetest.model.enumdiscriminator.types.Dog :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -155,11 +156,12 @@ async def put_extensible_model( """ @distributed_trace_async - async def put_extensible_model(self, input: Union[_models.Dog, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_extensible_model(self, input: Union[_models.Dog, _types.Dog, IO[bytes]], **kwargs: Any) -> None: """Send model with extensible enum discriminator type. - :param input: Dog to create. Is one of the following types: Dog, JSON, IO[bytes] Required. - :type input: ~typetest.model.enumdiscriminator.models.Dog or JSON or IO[bytes] + :param input: Dog to create. Is either a Dog type or a IO[bytes] type. Required. + :type input: ~typetest.model.enumdiscriminator.models.Dog or + ~typetest.model.enumdiscriminator.types.Dog or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -400,11 +402,13 @@ async def put_fixed_model( """ @overload - async def put_fixed_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_fixed_model( + self, input: _types.Snake, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Send model with fixed enum discriminator type. :param input: Snake to create. Required. - :type input: JSON + :type input: ~typetest.model.enumdiscriminator.types.Snake :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -428,11 +432,12 @@ async def put_fixed_model(self, input: IO[bytes], *, content_type: str = "applic """ @distributed_trace_async - async def put_fixed_model(self, input: Union[_models.Snake, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_fixed_model(self, input: Union[_models.Snake, _types.Snake, IO[bytes]], **kwargs: Any) -> None: """Send model with fixed enum discriminator type. - :param input: Snake to create. Is one of the following types: Snake, JSON, IO[bytes] Required. - :type input: ~typetest.model.enumdiscriminator.models.Snake or JSON or IO[bytes] + :param input: Snake to create. Is either a Snake type or a IO[bytes] type. Required. + :type input: ~typetest.model.enumdiscriminator.models.Snake or + ~typetest.model.enumdiscriminator.types.Snake or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/types.py index d150e7f4ab6d..5cb05b88ad7e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/types.py @@ -18,7 +18,7 @@ class Cobra(TypedDict, total=False): :ivar length: Length of the snake. Required. :vartype length: int :ivar kind: discriminator property. Required. Species cobra. - :vartype kind: str or ~typetest.model.enumdiscriminator.models.COBRA + :vartype kind: Literal[SnakeKind.COBRA] """ length: Required[int] @@ -33,7 +33,7 @@ class Golden(TypedDict, total=False): :ivar weight: Weight of the dog. Required. :vartype weight: int :ivar kind: discriminator property. Required. Species golden. - :vartype kind: str or ~typetest.model.enumdiscriminator.models.GOLDEN + :vartype kind: Literal[DogKind.GOLDEN] """ weight: Required[int] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/pyproject.toml index d5744413ccee..c853b85c0421 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_operations.py index ed67a5d59fd5..8254f31a33e0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import NestedDiscriminatorClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -208,11 +207,11 @@ def put_model(self, input: _models.Fish, *, content_type: str = "application/jso """ @overload - def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model(self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.nesteddiscriminator.types.Fish :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -237,12 +236,13 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", @distributed_trace def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Fish, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any ) -> None: """put_model. - :param input: Is one of the following types: Fish, JSON, IO[bytes] Required. - :type input: ~typetest.model.nesteddiscriminator.models.Fish or JSON or IO[bytes] + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.nesteddiscriminator.models.Fish or + ~typetest.model.nesteddiscriminator.types.Fish or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -367,11 +367,11 @@ def put_recursive_model( """ @overload - def put_recursive_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_recursive_model(self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_recursive_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.nesteddiscriminator.types.Fish :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -396,12 +396,13 @@ def put_recursive_model(self, input: IO[bytes], *, content_type: str = "applicat @distributed_trace def put_recursive_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Fish, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any ) -> None: """put_recursive_model. - :param input: Is one of the following types: Fish, JSON, IO[bytes] Required. - :type input: ~typetest.model.nesteddiscriminator.models.Fish or JSON or IO[bytes] + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.nesteddiscriminator.models.Fish or + ~typetest.model.nesteddiscriminator.types.Fish or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_operations.py index 18e477d93655..b291642ecc69 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_nested_discriminator_get_missing_discriminator_request, build_nested_discriminator_get_model_request, @@ -40,7 +40,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import NestedDiscriminatorClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -121,11 +120,11 @@ async def put_model(self, input: _models.Fish, *, content_type: str = "applicati """ @overload - async def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model(self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.nesteddiscriminator.types.Fish :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -149,11 +148,12 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def put_model(self, input: Union[_models.Fish, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_model(self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any) -> None: """put_model. - :param input: Is one of the following types: Fish, JSON, IO[bytes] Required. - :type input: ~typetest.model.nesteddiscriminator.models.Fish or JSON or IO[bytes] + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.nesteddiscriminator.models.Fish or + ~typetest.model.nesteddiscriminator.types.Fish or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -278,11 +278,13 @@ async def put_recursive_model( """ @overload - async def put_recursive_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_recursive_model( + self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_recursive_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.nesteddiscriminator.types.Fish :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -308,11 +310,12 @@ async def put_recursive_model( """ @distributed_trace_async - async def put_recursive_model(self, input: Union[_models.Fish, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_recursive_model(self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any) -> None: """put_recursive_model. - :param input: Is one of the following types: Fish, JSON, IO[bytes] Required. - :type input: ~typetest.model.nesteddiscriminator.models.Fish or JSON or IO[bytes] + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.nesteddiscriminator.models.Fish or + ~typetest.model.nesteddiscriminator.types.Fish or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/types.py index b401a3903a6b..bb86039e44a3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/types.py @@ -16,9 +16,9 @@ class GoblinShark(TypedDict, total=False): :ivar age: Required. :vartype age: int :ivar kind: Required. Default value is "shark". - :vartype kind: str + :vartype kind: Literal["shark"] :ivar sharktype: Required. Default value is "goblin". - :vartype sharktype: str + :vartype sharktype: Literal["goblin"] """ age: Required[int] @@ -36,13 +36,13 @@ class Salmon(TypedDict, total=False): :ivar age: Required. :vartype age: int :ivar kind: Required. Default value is "salmon". - :vartype kind: str + :vartype kind: Literal["salmon"] :ivar friends: - :vartype friends: list[~typetest.model.nesteddiscriminator.models.Fish] + :vartype friends: list["Fish"] :ivar hate: - :vartype hate: dict[str, ~typetest.model.nesteddiscriminator.models.Fish] + :vartype hate: dict[str, "Fish"] :ivar partner: - :vartype partner: ~typetest.model.nesteddiscriminator.models.Fish + :vartype partner: "Fish" """ age: Required[int] @@ -60,9 +60,9 @@ class SawShark(TypedDict, total=False): :ivar age: Required. :vartype age: int :ivar kind: Required. Default value is "shark". - :vartype kind: str + :vartype kind: Literal["shark"] :ivar sharktype: Required. Default value is "saw". - :vartype sharktype: str + :vartype sharktype: Literal["saw"] """ age: Required[int] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/README.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/pyproject.toml index f5f1a1907ac3..8c03b7d1993d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_operations/_operations.py index db8b9e39d6d6..ef8d2306e112 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_operations/_operations.py @@ -26,7 +26,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models, types +from .. import models as _models, types as _types from .._configuration import NotDiscriminatedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer @@ -103,7 +103,7 @@ def post_valid(self, input: _models.Siamese, *, content_type: str = "application """ @overload - def post_valid(self, input: types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: + def post_valid(self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: """post_valid. :param input: Required. @@ -132,7 +132,7 @@ def post_valid(self, input: IO[bytes], *, content_type: str = "application/json" @distributed_trace def post_valid( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Siamese, types.Siamese, IO[bytes]], **kwargs: Any + self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any ) -> None: """post_valid. @@ -264,7 +264,7 @@ def put_valid( @overload def put_valid( - self, input: types.Siamese, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Siamese: """put_valid. @@ -293,7 +293,7 @@ def put_valid(self, input: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace - def put_valid(self, input: Union[_models.Siamese, types.Siamese, IO[bytes]], **kwargs: Any) -> _models.Siamese: + def put_valid(self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any) -> _models.Siamese: """put_valid. :param input: Is either a Siamese type or a IO[bytes] type. Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/aio/_operations/_operations.py index 0d25bc178b81..c8a9ad732c41 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models, types +from ... import models as _models, types as _types from ..._operations._operations import ( build_not_discriminated_get_valid_request, build_not_discriminated_post_valid_request, @@ -62,7 +62,7 @@ async def post_valid( """ @overload - async def post_valid(self, input: types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def post_valid(self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: """post_valid. :param input: Required. @@ -90,7 +90,7 @@ async def post_valid(self, input: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def post_valid(self, input: Union[_models.Siamese, types.Siamese, IO[bytes]], **kwargs: Any) -> None: + async def post_valid(self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any) -> None: """post_valid. :param input: Is either a Siamese type or a IO[bytes] type. Required. @@ -221,7 +221,7 @@ async def put_valid( @overload async def put_valid( - self, input: types.Siamese, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Siamese: """put_valid. @@ -253,7 +253,7 @@ async def put_valid( @distributed_trace_async async def put_valid( - self, input: Union[_models.Siamese, types.Siamese, IO[bytes]], **kwargs: Any + self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any ) -> _models.Siamese: """put_valid. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/pyproject.toml index 0011233d988a..ee6552813da4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_operations.py index e4283324c723..741b5cbea0d4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import NotDiscriminatedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -104,11 +103,11 @@ def post_valid(self, input: _models.Siamese, *, content_type: str = "application """ @overload - def post_valid(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def post_valid(self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: """post_valid. :param input: Required. - :type input: JSON + :type input: ~typetest.model.notdiscriminated.types.Siamese :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -133,12 +132,13 @@ def post_valid(self, input: IO[bytes], *, content_type: str = "application/json" @distributed_trace def post_valid( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Siamese, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any ) -> None: """post_valid. - :param input: Is one of the following types: Siamese, JSON, IO[bytes] Required. - :type input: ~typetest.model.notdiscriminated.models.Siamese or JSON or IO[bytes] + :param input: Is either a Siamese type or a IO[bytes] type. Required. + :type input: ~typetest.model.notdiscriminated.models.Siamese or + ~typetest.model.notdiscriminated.types.Siamese or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -263,11 +263,13 @@ def put_valid( """ @overload - def put_valid(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Siamese: + def put_valid( + self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Siamese: """put_valid. :param input: Required. - :type input: JSON + :type input: ~typetest.model.notdiscriminated.types.Siamese :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -291,11 +293,12 @@ def put_valid(self, input: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace - def put_valid(self, input: Union[_models.Siamese, JSON, IO[bytes]], **kwargs: Any) -> _models.Siamese: + def put_valid(self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any) -> _models.Siamese: """put_valid. - :param input: Is one of the following types: Siamese, JSON, IO[bytes] Required. - :type input: ~typetest.model.notdiscriminated.models.Siamese or JSON or IO[bytes] + :param input: Is either a Siamese type or a IO[bytes] type. Required. + :type input: ~typetest.model.notdiscriminated.models.Siamese or + ~typetest.model.notdiscriminated.types.Siamese or IO[bytes] :return: Siamese. The Siamese is compatible with MutableMapping :rtype: ~typetest.model.notdiscriminated.models.Siamese :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_operations.py index c1c3dd0de069..4f01660f91fd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_not_discriminated_get_valid_request, build_not_discriminated_post_valid_request, @@ -37,7 +37,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import NotDiscriminatedClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -63,11 +62,11 @@ async def post_valid( """ @overload - async def post_valid(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def post_valid(self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: """post_valid. :param input: Required. - :type input: JSON + :type input: ~typetest.model.notdiscriminated.types.Siamese :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -91,11 +90,12 @@ async def post_valid(self, input: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def post_valid(self, input: Union[_models.Siamese, JSON, IO[bytes]], **kwargs: Any) -> None: + async def post_valid(self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any) -> None: """post_valid. - :param input: Is one of the following types: Siamese, JSON, IO[bytes] Required. - :type input: ~typetest.model.notdiscriminated.models.Siamese or JSON or IO[bytes] + :param input: Is either a Siamese type or a IO[bytes] type. Required. + :type input: ~typetest.model.notdiscriminated.models.Siamese or + ~typetest.model.notdiscriminated.types.Siamese or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -220,11 +220,13 @@ async def put_valid( """ @overload - async def put_valid(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Siamese: + async def put_valid( + self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Siamese: """put_valid. :param input: Required. - :type input: JSON + :type input: ~typetest.model.notdiscriminated.types.Siamese :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -250,11 +252,14 @@ async def put_valid( """ @distributed_trace_async - async def put_valid(self, input: Union[_models.Siamese, JSON, IO[bytes]], **kwargs: Any) -> _models.Siamese: + async def put_valid( + self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any + ) -> _models.Siamese: """put_valid. - :param input: Is one of the following types: Siamese, JSON, IO[bytes] Required. - :type input: ~typetest.model.notdiscriminated.models.Siamese or JSON or IO[bytes] + :param input: Is either a Siamese type or a IO[bytes] type. Required. + :type input: ~typetest.model.notdiscriminated.models.Siamese or + ~typetest.model.notdiscriminated.types.Siamese or IO[bytes] :return: Siamese. The Siamese is compatible with MutableMapping :rtype: ~typetest.model.notdiscriminated.models.Siamese :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-notdiscriminated/typetest/model/notdiscriminated/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/pyproject.toml index 965483487c3e..b2ab322318fc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_operations/_operations.py index 6f88182c9608..6f573b77a078 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import RecursiveClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -87,11 +86,11 @@ def put(self, input: _models.Extension, *, content_type: str = "application/json """ @overload - def put(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, input: _types.Extension, *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param input: Required. - :type input: JSON + :type input: ~typetest.model.recursive.types.Extension :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -116,12 +115,13 @@ def put(self, input: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Extension, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Extension, _types.Extension, IO[bytes]], **kwargs: Any ) -> None: """put. - :param input: Is one of the following types: Extension, JSON, IO[bytes] Required. - :type input: ~typetest.model.recursive.models.Extension or JSON or IO[bytes] + :param input: Is either a Extension type or a IO[bytes] type. Required. + :type input: ~typetest.model.recursive.models.Extension or + ~typetest.model.recursive.types.Extension or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_operations/_operations.py index 65722b99b227..84cf97902cb3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_operations/_operations.py @@ -27,13 +27,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_recursive_get_request, build_recursive_put_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import RecursiveClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -57,11 +56,11 @@ async def put(self, input: _models.Extension, *, content_type: str = "applicatio """ @overload - async def put(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, input: _types.Extension, *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param input: Required. - :type input: JSON + :type input: ~typetest.model.recursive.types.Extension :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -85,11 +84,12 @@ async def put(self, input: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, input: Union[_models.Extension, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, input: Union[_models.Extension, _types.Extension, IO[bytes]], **kwargs: Any) -> None: """put. - :param input: Is one of the following types: Extension, JSON, IO[bytes] Required. - :type input: ~typetest.model.recursive.models.Extension or JSON or IO[bytes] + :param input: Is either a Extension type or a IO[bytes] type. Required. + :type input: ~typetest.model.recursive.models.Extension or + ~typetest.model.recursive.types.Extension or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/types.py index e188b395c2b3..4dfb93b9fdb3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-recursive/typetest/model/recursive/types.py @@ -13,7 +13,7 @@ class Element(TypedDict, total=False): """element. :ivar extension: - :vartype extension: list[~typetest.model.recursive.models.Extension] + :vartype extension: list["Extension"] """ extension: list["Extension"] @@ -23,7 +23,7 @@ class Extension(Element): """extension. :ivar extension: - :vartype extension: list[~typetest.model.recursive.models.Extension] + :vartype extension: list["Extension"] :ivar level: Required. :vartype level: int """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/README.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/apiview-properties.json index 3921b5baaa5d..b245d157d42d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/apiview-properties.json +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/apiview-properties.json @@ -4,6 +4,7 @@ "typetest.model.singlediscriminator.typeddict.models.Bird": "Type.Model.Inheritance.SingleDiscriminator.Bird", "typetest.model.singlediscriminator.typeddict.models.Dinosaur": "Type.Model.Inheritance.SingleDiscriminator.Dinosaur", "typetest.model.singlediscriminator.typeddict.models.Eagle": "Type.Model.Inheritance.SingleDiscriminator.Eagle", + "typetest.model.singlediscriminator.typeddict.models.Fish": "Type.Model.Inheritance.SingleDiscriminator.Fish", "typetest.model.singlediscriminator.typeddict.models.Goose": "Type.Model.Inheritance.SingleDiscriminator.Goose", "typetest.model.singlediscriminator.typeddict.models.SeaGull": "Type.Model.Inheritance.SingleDiscriminator.SeaGull", "typetest.model.singlediscriminator.typeddict.models.Sparrow": "Type.Model.Inheritance.SingleDiscriminator.Sparrow", @@ -21,7 +22,11 @@ "typetest.model.singlediscriminator.typeddict.SingleDiscriminatorClient.get_wrong_discriminator": "Type.Model.Inheritance.SingleDiscriminator.getWrongDiscriminator", "typetest.model.singlediscriminator.typeddict.aio.SingleDiscriminatorClient.get_wrong_discriminator": "Type.Model.Inheritance.SingleDiscriminator.getWrongDiscriminator", "typetest.model.singlediscriminator.typeddict.SingleDiscriminatorClient.get_legacy_model": "Type.Model.Inheritance.SingleDiscriminator.getLegacyModel", - "typetest.model.singlediscriminator.typeddict.aio.SingleDiscriminatorClient.get_legacy_model": "Type.Model.Inheritance.SingleDiscriminator.getLegacyModel" + "typetest.model.singlediscriminator.typeddict.aio.SingleDiscriminatorClient.get_legacy_model": "Type.Model.Inheritance.SingleDiscriminator.getLegacyModel", + "typetest.model.singlediscriminator.typeddict.SingleDiscriminatorClient.get_no_subtypes_model": "Type.Model.Inheritance.SingleDiscriminator.getNoSubtypesModel", + "typetest.model.singlediscriminator.typeddict.aio.SingleDiscriminatorClient.get_no_subtypes_model": "Type.Model.Inheritance.SingleDiscriminator.getNoSubtypesModel", + "typetest.model.singlediscriminator.typeddict.SingleDiscriminatorClient.put_no_subtypes_model": "Type.Model.Inheritance.SingleDiscriminator.putNoSubtypesModel", + "typetest.model.singlediscriminator.typeddict.aio.SingleDiscriminatorClient.put_no_subtypes_model": "Type.Model.Inheritance.SingleDiscriminator.putNoSubtypesModel" }, - "CrossLanguageVersion": "301c4a3b5af0" + "CrossLanguageVersion": "d008d2bf96fe" } \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/generated_tests/test_single_discriminator.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/generated_tests/test_single_discriminator.py index efc2bac6ce87..f7e9308eda90 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/generated_tests/test_single_discriminator.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/generated_tests/test_single_discriminator.py @@ -78,3 +78,23 @@ def test_get_legacy_model(self, singlediscriminator_endpoint): # please add some check logic here by yourself # ... + + @SingleDiscriminatorPreparer() + @recorded_by_proxy + def test_get_no_subtypes_model(self, singlediscriminator_endpoint): + client = self.create_client(endpoint=singlediscriminator_endpoint) + response = client.get_no_subtypes_model() + + # please add some check logic here by yourself + # ... + + @SingleDiscriminatorPreparer() + @recorded_by_proxy + def test_put_no_subtypes_model(self, singlediscriminator_endpoint): + client = self.create_client(endpoint=singlediscriminator_endpoint) + response = client.put_no_subtypes_model( + input={"size": 0}, + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/generated_tests/test_single_discriminator_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/generated_tests/test_single_discriminator_async.py index 96fc035088f9..3dc0ab48e048 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/generated_tests/test_single_discriminator_async.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/generated_tests/test_single_discriminator_async.py @@ -79,3 +79,23 @@ async def test_get_legacy_model(self, singlediscriminator_endpoint): # please add some check logic here by yourself # ... + + @SingleDiscriminatorPreparer() + @recorded_by_proxy_async + async def test_get_no_subtypes_model(self, singlediscriminator_endpoint): + client = self.create_async_client(endpoint=singlediscriminator_endpoint) + response = await client.get_no_subtypes_model() + + # please add some check logic here by yourself + # ... + + @SingleDiscriminatorPreparer() + @recorded_by_proxy_async + async def test_put_no_subtypes_model(self, singlediscriminator_endpoint): + client = self.create_async_client(endpoint=singlediscriminator_endpoint) + response = await client.put_no_subtypes_model( + input={"size": 0}, + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/pyproject.toml index d32e779d393e..754194700646 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_operations/_operations.py index a8dba785e273..2fdc1053bdcb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_operations/_operations.py @@ -26,7 +26,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models, types +from .. import models as _models, types as _types from .._configuration import SingleDiscriminatorClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer @@ -145,6 +145,38 @@ def build_single_discriminator_get_legacy_model_request(**kwargs: Any) -> HttpRe return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) +def build_single_discriminator_get_no_subtypes_model_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/type/model/inheritance/single-discriminator/no-subtypes/model" + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_single_discriminator_put_no_subtypes_model_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/type/model/inheritance/single-discriminator/no-subtypes/model" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + class _SingleDiscriminatorClientOperationsMixin( ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SingleDiscriminatorClientConfiguration] ): @@ -221,7 +253,7 @@ def put_model(self, input: _models.Bird, *, content_type: str = "application/jso """ @overload - def put_model(self, input: types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. @@ -250,7 +282,7 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", @distributed_trace def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Bird, types.Bird, IO[bytes]], **kwargs: Any + self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any ) -> None: """put_model. @@ -381,7 +413,7 @@ def put_recursive_model( """ @overload - def put_recursive_model(self, input: types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_recursive_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_recursive_model. :param input: Required. @@ -410,7 +442,7 @@ def put_recursive_model(self, input: IO[bytes], *, content_type: str = "applicat @distributed_trace def put_recursive_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Bird, types.Bird, IO[bytes]], **kwargs: Any + self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any ) -> None: """put_recursive_model. @@ -637,3 +669,165 @@ def get_legacy_model(self, **kwargs: Any) -> _models.Dinosaur: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + @distributed_trace + def get_no_subtypes_model(self, **kwargs: Any) -> _models.Fish: + """get_no_subtypes_model. + + :return: Fish. The Fish is compatible with MutableMapping + :rtype: ~typetest.model.singlediscriminator.typeddict.models.Fish + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Fish] = kwargs.pop("cls", None) + + _request = build_single_discriminator_get_no_subtypes_model_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Fish, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def put_no_subtypes_model( + self, input: _models.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.typeddict.models.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put_no_subtypes_model( + self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.typeddict.types.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put_no_subtypes_model(self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put_no_subtypes_model( # pylint: disable=inconsistent-return-statements + self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.typeddict.models.Fish or + ~typetest.model.singlediscriminator.typeddict.types.Fish or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(input, (IOBase, bytes)): + _content = input + else: + _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_single_discriminator_put_no_subtypes_model_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/aio/_operations/_operations.py index 52061f94dec2..e94a4b242002 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/aio/_operations/_operations.py @@ -27,14 +27,16 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models, types +from ... import models as _models, types as _types from ..._operations._operations import ( build_single_discriminator_get_legacy_model_request, build_single_discriminator_get_missing_discriminator_request, build_single_discriminator_get_model_request, + build_single_discriminator_get_no_subtypes_model_request, build_single_discriminator_get_recursive_model_request, build_single_discriminator_get_wrong_discriminator_request, build_single_discriminator_put_model_request, + build_single_discriminator_put_no_subtypes_model_request, build_single_discriminator_put_recursive_model_request, ) from ..._utils.model_base import SdkJSONEncoder, _deserialize @@ -121,7 +123,7 @@ async def put_model(self, input: _models.Bird, *, content_type: str = "applicati """ @overload - async def put_model(self, input: types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. @@ -149,7 +151,7 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def put_model(self, input: Union[_models.Bird, types.Bird, IO[bytes]], **kwargs: Any) -> None: + async def put_model(self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any) -> None: """put_model. :param input: Is either a Bird type or a IO[bytes] type. Required. @@ -280,7 +282,7 @@ async def put_recursive_model( @overload async def put_recursive_model( - self, input: types.Bird, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any ) -> None: """put_recursive_model. @@ -311,7 +313,7 @@ async def put_recursive_model( """ @distributed_trace_async - async def put_recursive_model(self, input: Union[_models.Bird, types.Bird, IO[bytes]], **kwargs: Any) -> None: + async def put_recursive_model(self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any) -> None: """put_recursive_model. :param input: Is either a Bird type or a IO[bytes] type. Required. @@ -537,3 +539,165 @@ async def get_legacy_model(self, **kwargs: Any) -> _models.Dinosaur: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + @distributed_trace_async + async def get_no_subtypes_model(self, **kwargs: Any) -> _models.Fish: + """get_no_subtypes_model. + + :return: Fish. The Fish is compatible with MutableMapping + :rtype: ~typetest.model.singlediscriminator.typeddict.models.Fish + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Fish] = kwargs.pop("cls", None) + + _request = build_single_discriminator_get_no_subtypes_model_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Fish, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def put_no_subtypes_model( + self, input: _models.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.typeddict.models.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put_no_subtypes_model( + self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.typeddict.types.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put_no_subtypes_model( + self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put_no_subtypes_model(self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any) -> None: + """put_no_subtypes_model. + + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.typeddict.models.Fish or + ~typetest.model.singlediscriminator.typeddict.types.Fish or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(input, (IOBase, bytes)): + _content = input + else: + _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_single_discriminator_put_no_subtypes_model_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/__init__.py index b19768d50489..b1c0c1efb588 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/__init__.py @@ -17,6 +17,7 @@ Bird, Dinosaur, Eagle, + Fish, Goose, SeaGull, Sparrow, @@ -30,6 +31,7 @@ "Bird", "Dinosaur", "Eagle", + "Fish", "Goose", "SeaGull", "Sparrow", diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/_models.py index a913719f17d3..59b84682a81f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/_models.py @@ -135,6 +135,39 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.kind = "eagle" # type: ignore +class Fish(_Model): + """A discriminated model with no defined subtypes. The discriminator is declared but no models + extend it. + + :ivar kind: Required. + :vartype kind: str + :ivar size: Required. + :vartype size: int + """ + + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + size: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + size: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class Goose(Bird, discriminator="goose"): """The second level model in polymorphic single level inheritance. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/types.py index 22565fd954d4..d8602e6ed87c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/types.py @@ -17,13 +17,13 @@ class Eagle(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "eagle". - :vartype kind: str + :vartype kind: Literal["eagle"] :ivar friends: - :vartype friends: list[~typetest.model.singlediscriminator.typeddict.models.Bird] + :vartype friends: list["Bird"] :ivar hate: - :vartype hate: dict[str, ~typetest.model.singlediscriminator.typeddict.models.Bird] + :vartype hate: dict[str, "Bird"] :ivar partner: - :vartype partner: ~typetest.model.singlediscriminator.typeddict.models.Bird + :vartype partner: "Bird" """ wingspan: Required[int] @@ -35,13 +35,29 @@ class Eagle(TypedDict, total=False): partner: "Bird" +class Fish(TypedDict, total=False): + """A discriminated model with no defined subtypes. The discriminator is declared but no models + extend it. + + :ivar kind: Required. + :vartype kind: str + :ivar size: Required. + :vartype size: int + """ + + kind: Required[str] + """Required.""" + size: Required[int] + """Required.""" + + class Goose(TypedDict, total=False): """The second level model in polymorphic single level inheritance. :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "goose". - :vartype kind: str + :vartype kind: Literal["goose"] """ wingspan: Required[int] @@ -56,7 +72,7 @@ class SeaGull(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "seagull". - :vartype kind: str + :vartype kind: Literal["seagull"] """ wingspan: Required[int] @@ -71,7 +87,7 @@ class Sparrow(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "sparrow". - :vartype kind: str + :vartype kind: Literal["sparrow"] """ wingspan: Required[int] @@ -80,20 +96,4 @@ class Sparrow(TypedDict, total=False): """Required. Default value is \"sparrow\".""" -class TRex(TypedDict, total=False): - """The second level legacy model in polymorphic single level inheritance. - - :ivar size: Required. - :vartype size: int - :ivar kind: Required. Default value is "t-rex". - :vartype kind: str - """ - - size: Required[int] - """Required.""" - kind: Required[Literal["t-rex"]] - """Required. Default value is \"t-rex\".""" - - Bird = Union[Eagle, Goose, SeaGull, Sparrow] -Dinosaur = Union[TRex] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/apiview-properties.json b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/apiview-properties.json index ed7d784fa918..2f3040e9c344 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/apiview-properties.json +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/apiview-properties.json @@ -4,6 +4,7 @@ "typetest.model.singlediscriminator.models.Bird": "Type.Model.Inheritance.SingleDiscriminator.Bird", "typetest.model.singlediscriminator.models.Dinosaur": "Type.Model.Inheritance.SingleDiscriminator.Dinosaur", "typetest.model.singlediscriminator.models.Eagle": "Type.Model.Inheritance.SingleDiscriminator.Eagle", + "typetest.model.singlediscriminator.models.Fish": "Type.Model.Inheritance.SingleDiscriminator.Fish", "typetest.model.singlediscriminator.models.Goose": "Type.Model.Inheritance.SingleDiscriminator.Goose", "typetest.model.singlediscriminator.models.SeaGull": "Type.Model.Inheritance.SingleDiscriminator.SeaGull", "typetest.model.singlediscriminator.models.Sparrow": "Type.Model.Inheritance.SingleDiscriminator.Sparrow", @@ -21,7 +22,11 @@ "typetest.model.singlediscriminator.SingleDiscriminatorClient.get_wrong_discriminator": "Type.Model.Inheritance.SingleDiscriminator.getWrongDiscriminator", "typetest.model.singlediscriminator.aio.SingleDiscriminatorClient.get_wrong_discriminator": "Type.Model.Inheritance.SingleDiscriminator.getWrongDiscriminator", "typetest.model.singlediscriminator.SingleDiscriminatorClient.get_legacy_model": "Type.Model.Inheritance.SingleDiscriminator.getLegacyModel", - "typetest.model.singlediscriminator.aio.SingleDiscriminatorClient.get_legacy_model": "Type.Model.Inheritance.SingleDiscriminator.getLegacyModel" + "typetest.model.singlediscriminator.aio.SingleDiscriminatorClient.get_legacy_model": "Type.Model.Inheritance.SingleDiscriminator.getLegacyModel", + "typetest.model.singlediscriminator.SingleDiscriminatorClient.get_no_subtypes_model": "Type.Model.Inheritance.SingleDiscriminator.getNoSubtypesModel", + "typetest.model.singlediscriminator.aio.SingleDiscriminatorClient.get_no_subtypes_model": "Type.Model.Inheritance.SingleDiscriminator.getNoSubtypesModel", + "typetest.model.singlediscriminator.SingleDiscriminatorClient.put_no_subtypes_model": "Type.Model.Inheritance.SingleDiscriminator.putNoSubtypesModel", + "typetest.model.singlediscriminator.aio.SingleDiscriminatorClient.put_no_subtypes_model": "Type.Model.Inheritance.SingleDiscriminator.putNoSubtypesModel" }, - "CrossLanguageVersion": "301c4a3b5af0" + "CrossLanguageVersion": "d008d2bf96fe" } \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/generated_tests/test_single_discriminator.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/generated_tests/test_single_discriminator.py index efc2bac6ce87..f7e9308eda90 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/generated_tests/test_single_discriminator.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/generated_tests/test_single_discriminator.py @@ -78,3 +78,23 @@ def test_get_legacy_model(self, singlediscriminator_endpoint): # please add some check logic here by yourself # ... + + @SingleDiscriminatorPreparer() + @recorded_by_proxy + def test_get_no_subtypes_model(self, singlediscriminator_endpoint): + client = self.create_client(endpoint=singlediscriminator_endpoint) + response = client.get_no_subtypes_model() + + # please add some check logic here by yourself + # ... + + @SingleDiscriminatorPreparer() + @recorded_by_proxy + def test_put_no_subtypes_model(self, singlediscriminator_endpoint): + client = self.create_client(endpoint=singlediscriminator_endpoint) + response = client.put_no_subtypes_model( + input={"size": 0}, + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/generated_tests/test_single_discriminator_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/generated_tests/test_single_discriminator_async.py index 96fc035088f9..3dc0ab48e048 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/generated_tests/test_single_discriminator_async.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/generated_tests/test_single_discriminator_async.py @@ -79,3 +79,23 @@ async def test_get_legacy_model(self, singlediscriminator_endpoint): # please add some check logic here by yourself # ... + + @SingleDiscriminatorPreparer() + @recorded_by_proxy_async + async def test_get_no_subtypes_model(self, singlediscriminator_endpoint): + client = self.create_async_client(endpoint=singlediscriminator_endpoint) + response = await client.get_no_subtypes_model() + + # please add some check logic here by yourself + # ... + + @SingleDiscriminatorPreparer() + @recorded_by_proxy_async + async def test_put_no_subtypes_model(self, singlediscriminator_endpoint): + client = self.create_async_client(endpoint=singlediscriminator_endpoint) + response = await client.put_no_subtypes_model( + input={"size": 0}, + ) + + # please add some check logic here by yourself + # ... diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/pyproject.toml index d685d72a8c14..ccec4a7b7d63 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_operations.py index 0ecb0db4888d..cc726722e579 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import SingleDiscriminatorClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -146,6 +145,38 @@ def build_single_discriminator_get_legacy_model_request(**kwargs: Any) -> HttpRe return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) +def build_single_discriminator_get_no_subtypes_model_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/type/model/inheritance/single-discriminator/no-subtypes/model" + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_single_discriminator_put_no_subtypes_model_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/type/model/inheritance/single-discriminator/no-subtypes/model" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + class _SingleDiscriminatorClientOperationsMixin( ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SingleDiscriminatorClientConfiguration] ): @@ -222,11 +253,11 @@ def put_model(self, input: _models.Bird, *, content_type: str = "application/jso """ @overload - def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.singlediscriminator.types.Bird :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -251,12 +282,13 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", @distributed_trace def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Bird, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any ) -> None: """put_model. - :param input: Is one of the following types: Bird, JSON, IO[bytes] Required. - :type input: ~typetest.model.singlediscriminator.models.Bird or JSON or IO[bytes] + :param input: Is either a Bird type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Bird or + ~typetest.model.singlediscriminator.types.Bird or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -381,11 +413,11 @@ def put_recursive_model( """ @overload - def put_recursive_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_recursive_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_recursive_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.singlediscriminator.types.Bird :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -410,12 +442,13 @@ def put_recursive_model(self, input: IO[bytes], *, content_type: str = "applicat @distributed_trace def put_recursive_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Bird, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any ) -> None: """put_recursive_model. - :param input: Is one of the following types: Bird, JSON, IO[bytes] Required. - :type input: ~typetest.model.singlediscriminator.models.Bird or JSON or IO[bytes] + :param input: Is either a Bird type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Bird or + ~typetest.model.singlediscriminator.types.Bird or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -636,3 +669,165 @@ def get_legacy_model(self, **kwargs: Any) -> _models.Dinosaur: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + @distributed_trace + def get_no_subtypes_model(self, **kwargs: Any) -> _models.Fish: + """get_no_subtypes_model. + + :return: Fish. The Fish is compatible with MutableMapping + :rtype: ~typetest.model.singlediscriminator.models.Fish + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Fish] = kwargs.pop("cls", None) + + _request = build_single_discriminator_get_no_subtypes_model_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Fish, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def put_no_subtypes_model( + self, input: _models.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.models.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put_no_subtypes_model( + self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.types.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put_no_subtypes_model(self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put_no_subtypes_model( # pylint: disable=inconsistent-return-statements + self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Fish or + ~typetest.model.singlediscriminator.types.Fish or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(input, (IOBase, bytes)): + _content = input + else: + _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_single_discriminator_put_no_subtypes_model_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_operations.py index 49b6b70fab7d..514f9bc24d62 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_operations.py @@ -27,21 +27,22 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_single_discriminator_get_legacy_model_request, build_single_discriminator_get_missing_discriminator_request, build_single_discriminator_get_model_request, + build_single_discriminator_get_no_subtypes_model_request, build_single_discriminator_get_recursive_model_request, build_single_discriminator_get_wrong_discriminator_request, build_single_discriminator_put_model_request, + build_single_discriminator_put_no_subtypes_model_request, build_single_discriminator_put_recursive_model_request, ) from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import SingleDiscriminatorClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -122,11 +123,11 @@ async def put_model(self, input: _models.Bird, *, content_type: str = "applicati """ @overload - async def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.singlediscriminator.types.Bird :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -150,11 +151,12 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def put_model(self, input: Union[_models.Bird, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_model(self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any) -> None: """put_model. - :param input: Is one of the following types: Bird, JSON, IO[bytes] Required. - :type input: ~typetest.model.singlediscriminator.models.Bird or JSON or IO[bytes] + :param input: Is either a Bird type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Bird or + ~typetest.model.singlediscriminator.types.Bird or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -279,11 +281,13 @@ async def put_recursive_model( """ @overload - async def put_recursive_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_recursive_model( + self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_recursive_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.singlediscriminator.types.Bird :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -309,11 +313,12 @@ async def put_recursive_model( """ @distributed_trace_async - async def put_recursive_model(self, input: Union[_models.Bird, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_recursive_model(self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any) -> None: """put_recursive_model. - :param input: Is one of the following types: Bird, JSON, IO[bytes] Required. - :type input: ~typetest.model.singlediscriminator.models.Bird or JSON or IO[bytes] + :param input: Is either a Bird type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Bird or + ~typetest.model.singlediscriminator.types.Bird or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -534,3 +539,165 @@ async def get_legacy_model(self, **kwargs: Any) -> _models.Dinosaur: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + @distributed_trace_async + async def get_no_subtypes_model(self, **kwargs: Any) -> _models.Fish: + """get_no_subtypes_model. + + :return: Fish. The Fish is compatible with MutableMapping + :rtype: ~typetest.model.singlediscriminator.models.Fish + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Fish] = kwargs.pop("cls", None) + + _request = build_single_discriminator_get_no_subtypes_model_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Fish, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def put_no_subtypes_model( + self, input: _models.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.models.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put_no_subtypes_model( + self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.types.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put_no_subtypes_model( + self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put_no_subtypes_model(self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any) -> None: + """put_no_subtypes_model. + + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Fish or + ~typetest.model.singlediscriminator.types.Fish or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(input, (IOBase, bytes)): + _content = input + else: + _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_single_discriminator_put_no_subtypes_model_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/__init__.py index b19768d50489..b1c0c1efb588 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/__init__.py @@ -17,6 +17,7 @@ Bird, Dinosaur, Eagle, + Fish, Goose, SeaGull, Sparrow, @@ -30,6 +31,7 @@ "Bird", "Dinosaur", "Eagle", + "Fish", "Goose", "SeaGull", "Sparrow", diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_models.py index bd074298a34f..34686e567023 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_models.py @@ -135,6 +135,39 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.kind = "eagle" # type: ignore +class Fish(_Model): + """A discriminated model with no defined subtypes. The discriminator is declared but no models + extend it. + + :ivar kind: Required. + :vartype kind: str + :ivar size: Required. + :vartype size: int + """ + + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + size: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + size: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class Goose(Bird, discriminator="goose"): """The second level model in polymorphic single level inheritance. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/types.py index 50051cb83259..d8602e6ed87c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-singlediscriminator/typetest/model/singlediscriminator/types.py @@ -17,13 +17,13 @@ class Eagle(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "eagle". - :vartype kind: str + :vartype kind: Literal["eagle"] :ivar friends: - :vartype friends: list[~typetest.model.singlediscriminator.models.Bird] + :vartype friends: list["Bird"] :ivar hate: - :vartype hate: dict[str, ~typetest.model.singlediscriminator.models.Bird] + :vartype hate: dict[str, "Bird"] :ivar partner: - :vartype partner: ~typetest.model.singlediscriminator.models.Bird + :vartype partner: "Bird" """ wingspan: Required[int] @@ -35,13 +35,29 @@ class Eagle(TypedDict, total=False): partner: "Bird" +class Fish(TypedDict, total=False): + """A discriminated model with no defined subtypes. The discriminator is declared but no models + extend it. + + :ivar kind: Required. + :vartype kind: str + :ivar size: Required. + :vartype size: int + """ + + kind: Required[str] + """Required.""" + size: Required[int] + """Required.""" + + class Goose(TypedDict, total=False): """The second level model in polymorphic single level inheritance. :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "goose". - :vartype kind: str + :vartype kind: Literal["goose"] """ wingspan: Required[int] @@ -56,7 +72,7 @@ class SeaGull(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "seagull". - :vartype kind: str + :vartype kind: Literal["seagull"] """ wingspan: Required[int] @@ -71,7 +87,7 @@ class Sparrow(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "sparrow". - :vartype kind: str + :vartype kind: Literal["sparrow"] """ wingspan: Required[int] @@ -80,20 +96,4 @@ class Sparrow(TypedDict, total=False): """Required. Default value is \"sparrow\".""" -class TRex(TypedDict, total=False): - """The second level legacy model in polymorphic single level inheritance. - - :ivar size: Required. - :vartype size: int - :ivar kind: Required. Default value is "t-rex". - :vartype kind: str - """ - - size: Required[int] - """Required.""" - kind: Required[Literal["t-rex"]] - """Required. Default value is \"t-rex\".""" - - Bird = Union[Eagle, Goose, SeaGull, Sparrow] -Dinosaur = Union[TRex] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/README.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/generated_tests/test_usage.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/generated_tests/test_usage.py index 7514cae181d8..038f62ae08fc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/generated_tests/test_usage.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/generated_tests/test_usage.py @@ -18,6 +18,7 @@ def test_input(self, usage_endpoint): client = self.create_client(endpoint=usage_endpoint) response = client.input( input={"requiredProp": "str"}, + content_type="str", ) # please add some check logic here by yourself @@ -38,6 +39,7 @@ def test_input_and_output(self, usage_endpoint): client = self.create_client(endpoint=usage_endpoint) response = client.input_and_output( body={"requiredProp": "str"}, + content_type="str", ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/generated_tests/test_usage_async.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/generated_tests/test_usage_async.py index c2a66f7642ba..fc635aca3bbf 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/generated_tests/test_usage_async.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/generated_tests/test_usage_async.py @@ -19,6 +19,7 @@ async def test_input(self, usage_endpoint): client = self.create_async_client(endpoint=usage_endpoint) response = await client.input( input={"requiredProp": "str"}, + content_type="str", ) # please add some check logic here by yourself @@ -39,6 +40,7 @@ async def test_input_and_output(self, usage_endpoint): client = self.create_async_client(endpoint=usage_endpoint) response = await client.input_and_output( body={"requiredProp": "str"}, + content_type="str", ) # please add some check logic here by yourself diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/pyproject.toml index ed6ec01a4baf..249fb535c88f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_operations/_operations.py index 3f1cdc0db660..d1034a1c0c06 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_operations/_operations.py @@ -6,8 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +from typing import Any, Callable, Optional, TypeVar from azure.core import PipelineClient from azure.core.exceptions import ( @@ -25,7 +24,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import types +from .. import types as _types from .._configuration import UsageClientConfiguration from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC @@ -37,18 +36,17 @@ _SERIALIZER.client_side_validation = False -def build_usage_input_request(**kwargs: Any) -> HttpRequest: +def build_usage_input_request(*, json: _types.InputRecord, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type: str = kwargs.pop("content_type") # Construct URL _url = "/type/model/usage/input" # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) def build_usage_output_request(**kwargs: Any) -> HttpRequest: @@ -65,69 +63,30 @@ def build_usage_output_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_usage_input_and_output_request(**kwargs: Any) -> HttpRequest: +def build_usage_input_and_output_request(*, json: _types.InputOutputRecord, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type: str = kwargs.pop("content_type") accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/type/model/usage/input-output" # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) class _UsageClientOperationsMixin(ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], UsageClientConfiguration]): - @overload - def input(self, input: types.InputRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: + @distributed_trace + def input(self, input: _types.InputRecord, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """input. :param input: Required. :type input: ~typetest.model.usage.typeddictonly.types.InputRecord - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - input = { - "requiredProp": "str" - } - """ - - @overload - def input(self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: - """input. - - :param input: Required. - :type input: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def input( # pylint: disable=inconsistent-return-statements - self, input: Union[types.InputRecord, IO[bytes]], **kwargs: Any - ) -> None: - """input. - - :param input: Is either a InputRecord type or a IO[bytes] type. Required. - :type input: ~typetest.model.usage.typeddictonly.types.InputRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -151,21 +110,14 @@ def input( # pylint: disable=inconsistent-return-statements _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) cls: ClsType[None] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(input, (IOBase, bytes)): - _content = input - else: - _json = input + _json = input _request = build_usage_input_request( content_type=content_type, json=_json, - content=_content, headers=_headers, params=_params, ) @@ -189,7 +141,7 @@ def input( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def output(self, **kwargs: Any) -> types.OutputRecord: + def output(self, **kwargs: Any) -> _types.OutputRecord: """output. :return: OutputRecord @@ -215,7 +167,7 @@ def output(self, **kwargs: Any) -> types.OutputRecord: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[types.OutputRecord] = kwargs.pop("cls", None) + cls: ClsType[_types.OutputRecord] = kwargs.pop("cls", None) _request = build_usage_output_request( headers=_headers, @@ -256,67 +208,12 @@ def output(self, **kwargs: Any) -> types.OutputRecord: return deserialized # type: ignore - @overload - def input_and_output( - self, body: types.InputOutputRecord, *, content_type: str = "application/json", **kwargs: Any - ) -> types.InputOutputRecord: + @distributed_trace + def input_and_output(self, body: _types.InputOutputRecord, **kwargs: Any) -> _types.InputOutputRecord: """input_and_output. :param body: Required. :type body: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: InputOutputRecord - :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "requiredProp": "str" - } - - # response body for status code(s): 200 - response == { - "requiredProp": "str" - } - """ - - @overload - def input_and_output( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> types.InputOutputRecord: - """input_and_output. - - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: InputOutputRecord - :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "requiredProp": "str" - } - """ - - @distributed_trace - def input_and_output( - self, body: Union[types.InputOutputRecord, IO[bytes]], **kwargs: Any - ) -> types.InputOutputRecord: - """input_and_output. - - :param body: Is either a InputOutputRecord type or a IO[bytes] type. Required. - :type body: ~typetest.model.usage.typeddictonly.types.InputOutputRecord or IO[bytes] :return: InputOutputRecord :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord :raises ~azure.core.exceptions.HttpResponseError: @@ -345,21 +242,14 @@ def input_and_output( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[types.InputOutputRecord] = kwargs.pop("cls", None) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[_types.InputOutputRecord] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = body + _json = body _request = build_usage_input_and_output_request( content_type=content_type, json=_json, - content=_content, headers=_headers, params=_params, ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/aio/_operations/_operations.py index 2a6c727ec8ba..2ea6aeddb9bc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/aio/_operations/_operations.py @@ -7,8 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +from typing import Any, Callable, Optional, TypeVar from azure.core import AsyncPipelineClient from azure.core.exceptions import ( @@ -26,7 +25,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import types +from ... import types as _types from ..._operations._operations import ( build_usage_input_and_output_request, build_usage_input_request, @@ -43,48 +42,12 @@ class _UsageClientOperationsMixin( ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], UsageClientConfiguration] ): - @overload - async def input(self, input: types.InputRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: + @distributed_trace_async + async def input(self, input: _types.InputRecord, **kwargs: Any) -> None: """input. :param input: Required. :type input: ~typetest.model.usage.typeddictonly.types.InputRecord - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - input = { - "requiredProp": "str" - } - """ - - @overload - async def input(self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: - """input. - - :param input: Required. - :type input: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def input(self, input: Union[types.InputRecord, IO[bytes]], **kwargs: Any) -> None: - """input. - - :param input: Is either a InputRecord type or a IO[bytes] type. Required. - :type input: ~typetest.model.usage.typeddictonly.types.InputRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -108,21 +71,14 @@ async def input(self, input: Union[types.InputRecord, IO[bytes]], **kwargs: Any) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) cls: ClsType[None] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(input, (IOBase, bytes)): - _content = input - else: - _json = input + _json = input _request = build_usage_input_request( content_type=content_type, json=_json, - content=_content, headers=_headers, params=_params, ) @@ -146,7 +102,7 @@ async def input(self, input: Union[types.InputRecord, IO[bytes]], **kwargs: Any) return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def output(self, **kwargs: Any) -> types.OutputRecord: + async def output(self, **kwargs: Any) -> _types.OutputRecord: """output. :return: OutputRecord @@ -172,7 +128,7 @@ async def output(self, **kwargs: Any) -> types.OutputRecord: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[types.OutputRecord] = kwargs.pop("cls", None) + cls: ClsType[_types.OutputRecord] = kwargs.pop("cls", None) _request = build_usage_output_request( headers=_headers, @@ -213,67 +169,12 @@ async def output(self, **kwargs: Any) -> types.OutputRecord: return deserialized # type: ignore - @overload - async def input_and_output( - self, body: types.InputOutputRecord, *, content_type: str = "application/json", **kwargs: Any - ) -> types.InputOutputRecord: + @distributed_trace_async + async def input_and_output(self, body: _types.InputOutputRecord, **kwargs: Any) -> _types.InputOutputRecord: """input_and_output. :param body: Required. :type body: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: InputOutputRecord - :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "requiredProp": "str" - } - - # response body for status code(s): 200 - response == { - "requiredProp": "str" - } - """ - - @overload - async def input_and_output( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> types.InputOutputRecord: - """input_and_output. - - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: InputOutputRecord - :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "requiredProp": "str" - } - """ - - @distributed_trace_async - async def input_and_output( - self, body: Union[types.InputOutputRecord, IO[bytes]], **kwargs: Any - ) -> types.InputOutputRecord: - """input_and_output. - - :param body: Is either a InputOutputRecord type or a IO[bytes] type. Required. - :type body: ~typetest.model.usage.typeddictonly.types.InputOutputRecord or IO[bytes] :return: InputOutputRecord :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord :raises ~azure.core.exceptions.HttpResponseError: @@ -302,21 +203,14 @@ async def input_and_output( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[types.InputOutputRecord] = kwargs.pop("cls", None) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[_types.InputOutputRecord] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = body + _json = body _request = build_usage_input_and_output_request( content_type=content_type, json=_json, - content=_content, headers=_headers, params=_params, ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/pyproject.toml index 71671438384b..66eb372f640e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_operations/_operations.py index c569b49e617f..6960617a1094 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import UsageClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -102,11 +101,11 @@ def input(self, input: _models.InputRecord, *, content_type: str = "application/ """ @overload - def input(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def input(self, input: _types.InputRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """input. :param input: Required. - :type input: JSON + :type input: ~typetest.model.usage.types.InputRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -131,12 +130,13 @@ def input(self, input: IO[bytes], *, content_type: str = "application/json", **k @distributed_trace def input( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.InputRecord, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.InputRecord, _types.InputRecord, IO[bytes]], **kwargs: Any ) -> None: """input. - :param input: Is one of the following types: InputRecord, JSON, IO[bytes] Required. - :type input: ~typetest.model.usage.models.InputRecord or JSON or IO[bytes] + :param input: Is either a InputRecord type or a IO[bytes] type. Required. + :type input: ~typetest.model.usage.models.InputRecord or + ~typetest.model.usage.types.InputRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -262,12 +262,12 @@ def input_and_output( @overload def input_and_output( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.InputOutputRecord, *, content_type: str = "application/json", **kwargs: Any ) -> _models.InputOutputRecord: """input_and_output. :param body: Required. - :type body: JSON + :type body: ~typetest.model.usage.types.InputOutputRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -294,12 +294,13 @@ def input_and_output( @distributed_trace def input_and_output( - self, body: Union[_models.InputOutputRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.InputOutputRecord, _types.InputOutputRecord, IO[bytes]], **kwargs: Any ) -> _models.InputOutputRecord: """input_and_output. - :param body: Is one of the following types: InputOutputRecord, JSON, IO[bytes] Required. - :type body: ~typetest.model.usage.models.InputOutputRecord or JSON or IO[bytes] + :param body: Is either a InputOutputRecord type or a IO[bytes] type. Required. + :type body: ~typetest.model.usage.models.InputOutputRecord or + ~typetest.model.usage.types.InputOutputRecord or IO[bytes] :return: InputOutputRecord. The InputOutputRecord is compatible with MutableMapping :rtype: ~typetest.model.usage.models.InputOutputRecord :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_operations/_operations.py index 04ffc659584c..bf549328cc55 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_usage_input_and_output_request, build_usage_input_request, @@ -37,7 +37,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import UsageClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -61,11 +60,11 @@ async def input(self, input: _models.InputRecord, *, content_type: str = "applic """ @overload - async def input(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def input(self, input: _types.InputRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """input. :param input: Required. - :type input: JSON + :type input: ~typetest.model.usage.types.InputRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -89,11 +88,12 @@ async def input(self, input: IO[bytes], *, content_type: str = "application/json """ @distributed_trace_async - async def input(self, input: Union[_models.InputRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def input(self, input: Union[_models.InputRecord, _types.InputRecord, IO[bytes]], **kwargs: Any) -> None: """input. - :param input: Is one of the following types: InputRecord, JSON, IO[bytes] Required. - :type input: ~typetest.model.usage.models.InputRecord or JSON or IO[bytes] + :param input: Is either a InputRecord type or a IO[bytes] type. Required. + :type input: ~typetest.model.usage.models.InputRecord or + ~typetest.model.usage.types.InputRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -219,12 +219,12 @@ async def input_and_output( @overload async def input_and_output( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.InputOutputRecord, *, content_type: str = "application/json", **kwargs: Any ) -> _models.InputOutputRecord: """input_and_output. :param body: Required. - :type body: JSON + :type body: ~typetest.model.usage.types.InputOutputRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -251,12 +251,13 @@ async def input_and_output( @distributed_trace_async async def input_and_output( - self, body: Union[_models.InputOutputRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.InputOutputRecord, _types.InputOutputRecord, IO[bytes]], **kwargs: Any ) -> _models.InputOutputRecord: """input_and_output. - :param body: Is one of the following types: InputOutputRecord, JSON, IO[bytes] Required. - :type body: ~typetest.model.usage.models.InputOutputRecord or JSON or IO[bytes] + :param body: Is either a InputOutputRecord type or a IO[bytes] type. Required. + :type body: ~typetest.model.usage.models.InputOutputRecord or + ~typetest.model.usage.types.InputOutputRecord or IO[bytes] :return: InputOutputRecord. The InputOutputRecord is compatible with MutableMapping :rtype: ~typetest.model.usage.models.InputOutputRecord :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/types.py index 137fc8828b86..5a9eb1e1b64b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-usage/typetest/model/usage/types.py @@ -29,14 +29,3 @@ class InputRecord(TypedDict, total=False): requiredProp: Required[str] """Required.""" - - -class OutputRecord(TypedDict, total=False): - """Record used in operation return type. - - :ivar required_prop: Required. - :vartype required_prop: str - """ - - requiredProp: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/pyproject.toml index f9b7a1266131..27d7b25f0065 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_operations/_operations.py index a12442118fa1..cfc41f0922bb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import VisibilityClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -176,12 +175,12 @@ def get_model( @overload def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -212,12 +211,17 @@ def get_model( @distributed_trace def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -304,12 +308,12 @@ def head_model( @overload def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> bool: """head_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -340,12 +344,17 @@ def head_model( @distributed_trace def head_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> bool: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: bool @@ -417,11 +426,13 @@ def put_model( """ @overload - def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -446,12 +457,13 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", @distributed_trace def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -519,11 +531,13 @@ def patch_model( """ @overload - def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -548,12 +562,13 @@ def patch_model(self, input: IO[bytes], *, content_type: str = "application/json @distributed_trace def patch_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -621,11 +636,13 @@ def post_model( """ @overload - def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -650,12 +667,13 @@ def post_model(self, input: IO[bytes], *, content_type: str = "application/json" @distributed_trace def post_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -723,11 +741,13 @@ def delete_model( """ @overload - def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -752,12 +772,13 @@ def delete_model(self, input: IO[bytes], *, content_type: str = "application/jso @distributed_trace def delete_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -826,12 +847,12 @@ def put_read_only_model( @overload def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -858,12 +879,13 @@ def put_read_only_model( @distributed_trace def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.ReadOnlyModel or + ~typetest.model.visibility.types.ReadOnlyModel or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~typetest.model.visibility.models.ReadOnlyModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_operations/_operations.py index ecbe20e71497..35e33d8fcea7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_visibility_delete_model_request, build_visibility_get_model_request, @@ -41,7 +41,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import VisibilityClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -70,12 +69,12 @@ async def get_model( @overload async def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -106,12 +105,17 @@ async def get_model( @distributed_trace_async async def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -198,12 +202,12 @@ async def head_model( @overload async def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> bool: """head_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -234,12 +238,17 @@ async def head_model( @distributed_trace_async async def head_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> bool: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: bool @@ -311,11 +320,13 @@ async def put_model( """ @overload - async def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -339,11 +350,14 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ """ @distributed_trace_async - async def put_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -411,11 +425,13 @@ async def patch_model( """ @overload - async def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -439,11 +455,14 @@ async def patch_model(self, input: IO[bytes], *, content_type: str = "applicatio """ @distributed_trace_async - async def patch_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -511,11 +530,13 @@ async def post_model( """ @overload - async def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -539,11 +560,14 @@ async def post_model(self, input: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def post_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def post_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -611,11 +635,13 @@ async def delete_model( """ @overload - async def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -639,11 +665,14 @@ async def delete_model(self, input: IO[bytes], *, content_type: str = "applicati """ @distributed_trace_async - async def delete_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def delete_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -712,12 +741,12 @@ async def put_read_only_model( @overload async def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -744,12 +773,13 @@ async def put_read_only_model( @distributed_trace_async async def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.ReadOnlyModel or + ~typetest.model.visibility.types.ReadOnlyModel or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~typetest.model.visibility.models.ReadOnlyModel :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-model-visibility/typetest/model/visibility/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/pyproject.toml index ca73fe8b62d9..c6021a7f9f91 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_operations.py index 60c7ae7da088..f74efafc63f8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -96,7 +96,6 @@ ) from .._configuration import AdditionalPropertiesClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -195,11 +194,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.ExtendsUnknownAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -224,14 +225,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def put( - self, body: Union[_models.ExtendsUnknownAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ExtendsUnknownAdditionalProperties, _types.ExtendsUnknownAdditionalProperties, IO[bytes]], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsUnknownAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalProperties - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalProperties or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -383,11 +387,18 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.ExtendsUnknownAdditionalPropertiesDerived, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -412,15 +423,22 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def put( - self, body: Union[_models.ExtendsUnknownAdditionalPropertiesDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsUnknownAdditionalPropertiesDerived, + _types.ExtendsUnknownAdditionalPropertiesDerived, + IO[bytes], + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsUnknownAdditionalPropertiesDerived, - JSON, IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalPropertiesDerived type or a IO[bytes] + type. Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalPropertiesDerived or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDerived or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -572,11 +590,18 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.ExtendsUnknownAdditionalPropertiesDiscriminated, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDiscriminated :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -601,15 +626,23 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def put( - self, body: Union[_models.ExtendsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsUnknownAdditionalPropertiesDiscriminated, + _types.ExtendsUnknownAdditionalPropertiesDiscriminated, + IO[bytes], + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: - ExtendsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalPropertiesDiscriminated type or a + IO[bytes] type. Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalPropertiesDiscriminated - or JSON or IO[bytes] + or + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDiscriminated + or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -755,11 +788,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IsUnknownAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsUnknownAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -783,13 +818,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.IsUnknownAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.IsUnknownAdditionalProperties, _types.IsUnknownAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsUnknownAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -939,11 +978,17 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.IsUnknownAdditionalPropertiesDerived, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -968,14 +1013,19 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def put( - self, body: Union[_models.IsUnknownAdditionalPropertiesDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.IsUnknownAdditionalPropertiesDerived, _types.IsUnknownAdditionalPropertiesDerived, IO[bytes] + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalPropertiesDerived, JSON, - IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalPropertiesDerived type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalPropertiesDerived - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDerived or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1127,11 +1177,18 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.IsUnknownAdditionalPropertiesDiscriminated, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDiscriminated :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1156,15 +1213,22 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def put( - self, body: Union[_models.IsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.IsUnknownAdditionalPropertiesDiscriminated, + _types.IsUnknownAdditionalPropertiesDiscriminated, + IO[bytes], + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalPropertiesDiscriminated, - JSON, IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalPropertiesDiscriminated type or a IO[bytes] + type. Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalPropertiesDiscriminated or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDiscriminated or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1310,11 +1374,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.ExtendsStringAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsStringAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1338,13 +1404,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.ExtendsStringAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.ExtendsStringAdditionalProperties, _types.ExtendsStringAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsStringAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsStringAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsStringAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsStringAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1490,11 +1560,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IsStringAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsStringAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1518,13 +1590,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.IsStringAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.IsStringAdditionalProperties, _types.IsStringAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IsStringAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsStringAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsStringAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsStringAdditionalProperties or + ~typetest.property.additionalproperties.types.IsStringAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1669,11 +1744,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.SpreadStringRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadStringRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1697,12 +1774,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.SpreadStringRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.SpreadStringRecord, _types.SpreadStringRecord, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadStringRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadStringRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadStringRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadStringRecord or + ~typetest.property.additionalproperties.types.SpreadStringRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1848,11 +1927,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.ExtendsFloatAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsFloatAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1876,13 +1957,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.ExtendsFloatAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.ExtendsFloatAdditionalProperties, _types.ExtendsFloatAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsFloatAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsFloatAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsFloatAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsFloatAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2028,11 +2113,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IsFloatAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsFloatAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2056,13 +2143,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.IsFloatAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.IsFloatAdditionalProperties, _types.IsFloatAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IsFloatAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsFloatAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsFloatAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsFloatAdditionalProperties or + ~typetest.property.additionalproperties.types.IsFloatAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2207,11 +2297,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.SpreadFloatRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadFloatRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2235,12 +2327,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.SpreadFloatRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.SpreadFloatRecord, _types.SpreadFloatRecord, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadFloatRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadFloatRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadFloatRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadFloatRecord or + ~typetest.property.additionalproperties.types.SpreadFloatRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2386,11 +2480,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.ExtendsModelAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsModelAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2414,13 +2510,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.ExtendsModelAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.ExtendsModelAdditionalProperties, _types.ExtendsModelAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsModelAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsModelAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsModelAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsModelAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2566,11 +2666,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IsModelAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsModelAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2594,13 +2696,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.IsModelAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.IsModelAdditionalProperties, _types.IsModelAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IsModelAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsModelAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsModelAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsModelAdditionalProperties or + ~typetest.property.additionalproperties.types.IsModelAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2745,11 +2850,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.SpreadModelRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadModelRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2773,12 +2880,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.SpreadModelRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.SpreadModelRecord, _types.SpreadModelRecord, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadModelRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadModelRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadModelRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadModelRecord or + ~typetest.property.additionalproperties.types.SpreadModelRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2929,11 +3038,17 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.ExtendsModelArrayAdditionalProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsModelArrayAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2958,14 +3073,19 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def put( - self, body: Union[_models.ExtendsModelArrayAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsModelArrayAdditionalProperties, _types.ExtendsModelArrayAdditionalProperties, IO[bytes] + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsModelArrayAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsModelArrayAdditionalProperties type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.ExtendsModelArrayAdditionalProperties or JSON or + ~typetest.property.additionalproperties.models.ExtendsModelArrayAdditionalProperties or + ~typetest.property.additionalproperties.types.ExtendsModelArrayAdditionalProperties or IO[bytes] :return: None :rtype: None @@ -3112,11 +3232,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IsModelArrayAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsModelArrayAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3140,13 +3262,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.IsModelArrayAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.IsModelArrayAdditionalProperties, _types.IsModelArrayAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IsModelArrayAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a IsModelArrayAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsModelArrayAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsModelArrayAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3291,11 +3417,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.SpreadModelArrayRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadModelArrayRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3319,13 +3447,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.SpreadModelArrayRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.SpreadModelArrayRecord, _types.SpreadModelArrayRecord, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadModelArrayRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.SpreadModelArrayRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadModelArrayRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadModelArrayRecord or + ~typetest.property.additionalproperties.types.SpreadModelArrayRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3471,11 +3600,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadStringRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadStringRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3499,13 +3630,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DifferentSpreadStringRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadStringRecord, _types.DifferentSpreadStringRecord, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadStringRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadStringRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadStringRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3651,11 +3785,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadFloatRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadFloatRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3679,13 +3815,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DifferentSpreadFloatRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadFloatRecord, _types.DifferentSpreadFloatRecord, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadFloatRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadFloatRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadFloatRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3831,11 +3970,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadModelRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3859,13 +4000,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DifferentSpreadModelRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadModelRecord, _types.DifferentSpreadModelRecord, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadModelRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadModelRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4011,11 +4155,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadModelArrayRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4039,13 +4185,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DifferentSpreadModelArrayRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadModelArrayRecord, _types.DifferentSpreadModelArrayRecord, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelArrayRecord, JSON, - IO[bytes] Required. + :param body: body. Is either a DifferentSpreadModelArrayRecord type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelArrayRecord or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4191,11 +4341,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadStringDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadStringDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4219,13 +4371,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DifferentSpreadStringDerived, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadStringDerived, _types.DifferentSpreadStringDerived, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadStringDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadStringDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadStringDerived or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4371,11 +4526,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadFloatDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadFloatDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4399,13 +4556,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DifferentSpreadFloatDerived, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadFloatDerived, _types.DifferentSpreadFloatDerived, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadFloatDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadFloatDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadFloatDerived or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4551,11 +4711,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadModelDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4579,13 +4741,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DifferentSpreadModelDerived, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadModelDerived, _types.DifferentSpreadModelDerived, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadModelDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadModelDerived or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4731,11 +4896,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadModelArrayDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4759,13 +4926,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DifferentSpreadModelArrayDerived, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadModelArrayDerived, _types.DifferentSpreadModelArrayDerived, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelArrayDerived, JSON, - IO[bytes] Required. + :param body: body. Is either a DifferentSpreadModelArrayDerived type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelArrayDerived or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayDerived or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4910,11 +5081,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.MultipleSpreadRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.MultipleSpreadRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4938,13 +5111,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.MultipleSpreadRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.MultipleSpreadRecord, _types.MultipleSpreadRecord, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: MultipleSpreadRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.MultipleSpreadRecord or JSON or - IO[bytes] + :param body: body. Is either a MultipleSpreadRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.MultipleSpreadRecord or + ~typetest.property.additionalproperties.types.MultipleSpreadRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5089,11 +5263,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.SpreadRecordForUnion, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForUnion :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5117,13 +5293,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.SpreadRecordForUnion, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.SpreadRecordForUnion, _types.SpreadRecordForUnion, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForUnion, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.SpreadRecordForUnion or JSON or - IO[bytes] + :param body: body. Is either a SpreadRecordForUnion type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadRecordForUnion or + ~typetest.property.additionalproperties.types.SpreadRecordForUnion or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5273,11 +5450,17 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5302,14 +5485,19 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def put( - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion, _types.SpreadRecordForNonDiscriminatedUnion, IO[bytes] + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5460,11 +5648,17 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion2, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5489,14 +5683,19 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def put( - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion2, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion2, _types.SpreadRecordForNonDiscriminatedUnion2, IO[bytes] + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion2, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion2 type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion2 or JSON or + ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion2 or + ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion2 or IO[bytes] :return: None :rtype: None @@ -5648,11 +5847,17 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion3, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5677,14 +5882,19 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def put( - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion3, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion3, _types.SpreadRecordForNonDiscriminatedUnion3, IO[bytes] + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion3, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion3 type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion3 or JSON or + ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion3 or + ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion3 or IO[bytes] :return: None :rtype: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_operations.py index 1efb6517386e..e5be69d5aa17 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_operations.py @@ -27,12 +27,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import AdditionalPropertiesClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -1018,11 +1017,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.ExtendsUnknownAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1047,14 +1048,17 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsUnknownAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ExtendsUnknownAdditionalProperties, _types.ExtendsUnknownAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsUnknownAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalProperties - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalProperties or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1206,11 +1210,18 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.ExtendsUnknownAdditionalPropertiesDerived, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1235,15 +1246,22 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsUnknownAdditionalPropertiesDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsUnknownAdditionalPropertiesDerived, + _types.ExtendsUnknownAdditionalPropertiesDerived, + IO[bytes], + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsUnknownAdditionalPropertiesDerived, - JSON, IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalPropertiesDerived type or a IO[bytes] + type. Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalPropertiesDerived or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDerived or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1395,11 +1413,18 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.ExtendsUnknownAdditionalPropertiesDiscriminated, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDiscriminated :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1424,15 +1449,23 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsUnknownAdditionalPropertiesDiscriminated, + _types.ExtendsUnknownAdditionalPropertiesDiscriminated, + IO[bytes], + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: - ExtendsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalPropertiesDiscriminated type or a + IO[bytes] type. Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalPropertiesDiscriminated - or JSON or IO[bytes] + or + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDiscriminated + or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1578,11 +1611,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.IsUnknownAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsUnknownAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1607,14 +1642,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsUnknownAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.IsUnknownAdditionalProperties, _types.IsUnknownAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsUnknownAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1764,11 +1801,17 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.IsUnknownAdditionalPropertiesDerived, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1793,14 +1836,19 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsUnknownAdditionalPropertiesDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.IsUnknownAdditionalPropertiesDerived, _types.IsUnknownAdditionalPropertiesDerived, IO[bytes] + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalPropertiesDerived, JSON, - IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalPropertiesDerived type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalPropertiesDerived - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDerived or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1952,11 +2000,18 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.IsUnknownAdditionalPropertiesDiscriminated, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDiscriminated :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1981,15 +2036,22 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.IsUnknownAdditionalPropertiesDiscriminated, + _types.IsUnknownAdditionalPropertiesDiscriminated, + IO[bytes], + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalPropertiesDiscriminated, - JSON, IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalPropertiesDiscriminated type or a IO[bytes] + type. Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalPropertiesDiscriminated or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDiscriminated or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2135,11 +2197,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.ExtendsStringAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsStringAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2164,14 +2228,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsStringAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ExtendsStringAdditionalProperties, _types.ExtendsStringAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsStringAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsStringAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsStringAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsStringAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2317,11 +2383,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.IsStringAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsStringAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2346,14 +2414,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsStringAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.IsStringAdditionalProperties, _types.IsStringAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsStringAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsStringAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsStringAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsStringAdditionalProperties or + ~typetest.property.additionalproperties.types.IsStringAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2496,11 +2565,11 @@ def put(self, body: _models.SpreadStringRecord, *, content_type: str = "applicat """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.SpreadStringRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadStringRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2525,13 +2594,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadStringRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SpreadStringRecord, _types.SpreadStringRecord, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadStringRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadStringRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadStringRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadStringRecord or + ~typetest.property.additionalproperties.types.SpreadStringRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2677,11 +2746,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.ExtendsFloatAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsFloatAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2706,14 +2777,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsFloatAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ExtendsFloatAdditionalProperties, _types.ExtendsFloatAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsFloatAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsFloatAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsFloatAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsFloatAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2859,11 +2932,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.IsFloatAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsFloatAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2888,14 +2963,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsFloatAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.IsFloatAdditionalProperties, _types.IsFloatAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsFloatAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsFloatAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsFloatAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsFloatAdditionalProperties or + ~typetest.property.additionalproperties.types.IsFloatAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3038,11 +3114,11 @@ def put(self, body: _models.SpreadFloatRecord, *, content_type: str = "applicati """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.SpreadFloatRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadFloatRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3067,13 +3143,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadFloatRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SpreadFloatRecord, _types.SpreadFloatRecord, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadFloatRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadFloatRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadFloatRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadFloatRecord or + ~typetest.property.additionalproperties.types.SpreadFloatRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3219,11 +3295,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.ExtendsModelAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsModelAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3248,14 +3326,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsModelAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ExtendsModelAdditionalProperties, _types.ExtendsModelAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsModelAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsModelAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsModelAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsModelAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3401,11 +3481,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.IsModelAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsModelAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3430,14 +3512,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsModelAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.IsModelAdditionalProperties, _types.IsModelAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsModelAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsModelAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsModelAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsModelAdditionalProperties or + ~typetest.property.additionalproperties.types.IsModelAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3580,11 +3663,11 @@ def put(self, body: _models.SpreadModelRecord, *, content_type: str = "applicati """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.SpreadModelRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadModelRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3609,13 +3692,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadModelRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SpreadModelRecord, _types.SpreadModelRecord, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadModelRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadModelRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadModelRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadModelRecord or + ~typetest.property.additionalproperties.types.SpreadModelRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3766,11 +3849,17 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.ExtendsModelArrayAdditionalProperties, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsModelArrayAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3795,14 +3884,19 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsModelArrayAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsModelArrayAdditionalProperties, _types.ExtendsModelArrayAdditionalProperties, IO[bytes] + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsModelArrayAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsModelArrayAdditionalProperties type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.ExtendsModelArrayAdditionalProperties or JSON or + ~typetest.property.additionalproperties.models.ExtendsModelArrayAdditionalProperties or + ~typetest.property.additionalproperties.types.ExtendsModelArrayAdditionalProperties or IO[bytes] :return: None :rtype: None @@ -3949,11 +4043,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.IsModelArrayAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsModelArrayAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3978,14 +4074,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsModelArrayAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.IsModelArrayAdditionalProperties, _types.IsModelArrayAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsModelArrayAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a IsModelArrayAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsModelArrayAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsModelArrayAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4130,11 +4228,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.SpreadModelArrayRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadModelArrayRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4159,14 +4259,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadModelArrayRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SpreadModelArrayRecord, _types.SpreadModelArrayRecord, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadModelArrayRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.SpreadModelArrayRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadModelArrayRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadModelArrayRecord or + ~typetest.property.additionalproperties.types.SpreadModelArrayRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4312,11 +4411,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadStringRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadStringRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4341,14 +4442,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadStringRecord, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadStringRecord, _types.DifferentSpreadStringRecord, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadStringRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadStringRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadStringRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4494,11 +4596,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadFloatRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadFloatRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4523,14 +4627,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadFloatRecord, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadFloatRecord, _types.DifferentSpreadFloatRecord, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadFloatRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadFloatRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadFloatRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4676,11 +4781,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadModelRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4705,14 +4812,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadModelRecord, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadModelRecord, _types.DifferentSpreadModelRecord, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadModelRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadModelRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4858,11 +4966,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadModelArrayRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4887,14 +4997,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadModelArrayRecord, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadModelArrayRecord, _types.DifferentSpreadModelArrayRecord, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelArrayRecord, JSON, - IO[bytes] Required. + :param body: body. Is either a DifferentSpreadModelArrayRecord type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelArrayRecord or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5040,11 +5152,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadStringDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadStringDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5069,14 +5183,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadStringDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadStringDerived, _types.DifferentSpreadStringDerived, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadStringDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadStringDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadStringDerived or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5222,11 +5337,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadFloatDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadFloatDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5251,14 +5368,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadFloatDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadFloatDerived, _types.DifferentSpreadFloatDerived, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadFloatDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadFloatDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadFloatDerived or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5404,11 +5522,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadModelDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5433,14 +5553,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadModelDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadModelDerived, _types.DifferentSpreadModelDerived, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadModelDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadModelDerived or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5586,11 +5707,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadModelArrayDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5615,14 +5738,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadModelArrayDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadModelArrayDerived, _types.DifferentSpreadModelArrayDerived, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelArrayDerived, JSON, - IO[bytes] Required. + :param body: body. Is either a DifferentSpreadModelArrayDerived type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelArrayDerived or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayDerived or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5765,11 +5890,11 @@ def put(self, body: _models.MultipleSpreadRecord, *, content_type: str = "applic """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.MultipleSpreadRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.MultipleSpreadRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5794,14 +5919,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.MultipleSpreadRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.MultipleSpreadRecord, _types.MultipleSpreadRecord, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: MultipleSpreadRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.MultipleSpreadRecord or JSON or - IO[bytes] + :param body: body. Is either a MultipleSpreadRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.MultipleSpreadRecord or + ~typetest.property.additionalproperties.types.MultipleSpreadRecord or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5944,11 +6068,11 @@ def put(self, body: _models.SpreadRecordForUnion, *, content_type: str = "applic """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.SpreadRecordForUnion, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForUnion :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5973,14 +6097,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadRecordForUnion, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SpreadRecordForUnion, _types.SpreadRecordForUnion, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForUnion, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.SpreadRecordForUnion or JSON or - IO[bytes] + :param body: body. Is either a SpreadRecordForUnion type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadRecordForUnion or + ~typetest.property.additionalproperties.types.SpreadRecordForUnion or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6130,11 +6253,17 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -6159,14 +6288,19 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion, _types.SpreadRecordForNonDiscriminatedUnion, IO[bytes] + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion or + IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6317,11 +6451,17 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion2, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -6346,14 +6486,19 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion2, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion2, _types.SpreadRecordForNonDiscriminatedUnion2, IO[bytes] + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion2, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion2 type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion2 or JSON or + ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion2 or + ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion2 or IO[bytes] :return: None :rtype: None @@ -6505,11 +6650,17 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion3, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -6534,14 +6685,19 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion3, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion3, _types.SpreadRecordForNonDiscriminatedUnion3, IO[bytes] + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion3, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion3 type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion3 or JSON or + ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion3 or + ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion3 or IO[bytes] :return: None :rtype: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/types.py index 94285bc5681f..5aede8793bad 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-additionalproperties/typetest/property/additionalproperties/types.py @@ -6,7 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime from typing import Literal, Union from typing_extensions import Required, TypedDict @@ -54,7 +53,7 @@ class DifferentSpreadModelArrayDerived(DifferentSpreadModelArrayRecord): :ivar known_prop: Required. :vartype known_prop: str :ivar derived_prop: The index property. Required. - :vartype derived_prop: list[~typetest.property.additionalproperties.models.ModelForRecord] + :vartype derived_prop: list["ModelForRecord"] """ derivedProp: Required[list["ModelForRecord"]] @@ -79,7 +78,7 @@ class DifferentSpreadModelDerived(DifferentSpreadModelRecord): :ivar known_prop: Required. :vartype known_prop: str :ivar derived_prop: The index property. Required. - :vartype derived_prop: ~typetest.property.additionalproperties.models.ModelForRecord + :vartype derived_prop: "ModelForRecord" """ derivedProp: Required["ModelForRecord"] @@ -126,7 +125,7 @@ class ExtendsModelAdditionalProperties(TypedDict, total=False): """The model extends from Record type. :ivar known_prop: Required. - :vartype known_prop: ~typetest.property.additionalproperties.models.ModelForRecord + :vartype known_prop: "ModelForRecord" """ knownProp: Required["ModelForRecord"] @@ -137,7 +136,7 @@ class ExtendsModelArrayAdditionalProperties(TypedDict, total=False): """The model extends from Record type. :ivar known_prop: Required. - :vartype known_prop: list[~typetest.property.additionalproperties.models.ModelForRecord] + :vartype known_prop: list["ModelForRecord"] """ knownProp: Required[list["ModelForRecord"]] @@ -189,7 +188,7 @@ class ExtendsUnknownAdditionalPropertiesDiscriminatedDerived(TypedDict, total=Fa :ivar name: The name property. Required. :vartype name: str :ivar kind: Required. Default value is "derived". - :vartype kind: str + :vartype kind: Literal["derived"] :ivar index: The index property. Required. :vartype index: int :ivar age: The age property. @@ -221,7 +220,7 @@ class IsModelAdditionalProperties(TypedDict, total=False): """The model is from Record type. :ivar known_prop: Required. - :vartype known_prop: ~typetest.property.additionalproperties.models.ModelForRecord + :vartype known_prop: "ModelForRecord" """ knownProp: Required["ModelForRecord"] @@ -232,7 +231,7 @@ class IsModelArrayAdditionalProperties(TypedDict, total=False): """The model is from Record type. :ivar known_prop: Required. - :vartype known_prop: list[~typetest.property.additionalproperties.models.ModelForRecord] + :vartype known_prop: list["ModelForRecord"] """ knownProp: Required[list["ModelForRecord"]] @@ -284,7 +283,7 @@ class IsUnknownAdditionalPropertiesDiscriminatedDerived(TypedDict, total=False): :ivar name: The name property. Required. :vartype name: str :ivar kind: Required. Default value is "derived". - :vartype kind: str + :vartype kind: Literal["derived"] :ivar index: The index property. Required. :vartype index: int :ivar age: The age property. @@ -338,7 +337,7 @@ class SpreadModelArrayRecord(TypedDict, total=False): """SpreadModelArrayRecord. :ivar known_prop: Required. - :vartype known_prop: list[~typetest.property.additionalproperties.models.ModelForRecord] + :vartype known_prop: list["ModelForRecord"] """ knownProp: Required[list["ModelForRecord"]] @@ -349,7 +348,7 @@ class SpreadModelRecord(TypedDict, total=False): """The model spread Record with the same known property type. :ivar known_prop: Required. - :vartype known_prop: ~typetest.property.additionalproperties.models.ModelForRecord + :vartype known_prop: "ModelForRecord" """ knownProp: Required["ModelForRecord"] @@ -415,7 +414,7 @@ class WidgetData0(TypedDict, total=False): """WidgetData0. :ivar kind: Required. Default value is "kind0". - :vartype kind: str + :vartype kind: Literal["kind0"] :ivar foo_prop: Required. :vartype foo_prop: str """ @@ -430,25 +429,25 @@ class WidgetData1(TypedDict, total=False): """WidgetData1. :ivar kind: Required. Default value is "kind1". - :vartype kind: str + :vartype kind: Literal["kind1"] :ivar start: Required. - :vartype start: ~datetime.datetime + :vartype start: str :ivar end: - :vartype end: ~datetime.datetime + :vartype end: str """ kind: Required[Literal["kind1"]] """Required. Default value is \"kind1\".""" - start: Required[datetime.datetime] + start: Required[str] """Required.""" - end: datetime.datetime + end: str class WidgetData2(TypedDict, total=False): """WidgetData2. :ivar kind: Required. Default value is "kind1". - :vartype kind: str + :vartype kind: Literal["kind1"] :ivar start: Required. :vartype start: str """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/pyproject.toml index 087e4554c1a4..520e51d0ab3a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/operations/_operations.py index f55b50059216..879e095e58dc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -62,7 +62,6 @@ ) from .._configuration import NullableClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -216,12 +215,12 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.StringProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -247,11 +246,14 @@ async def patch_non_null( """ @distributed_trace_async - async def patch_non_null(self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_non_null( + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.StringProperty or + ~typetest.property.nullable.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -320,12 +322,12 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.StringProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -351,11 +353,14 @@ async def patch_null( """ @distributed_trace_async - async def patch_null(self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.StringProperty or + ~typetest.property.nullable.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -556,12 +561,12 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.BytesProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -587,11 +592,14 @@ async def patch_non_null( """ @distributed_trace_async - async def patch_non_null(self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_non_null( + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.BytesProperty or + ~typetest.property.nullable.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -660,12 +668,12 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.BytesProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -691,11 +699,14 @@ async def patch_null( """ @distributed_trace_async - async def patch_null(self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.BytesProperty or + ~typetest.property.nullable.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -896,12 +907,12 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.DatetimeProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -927,11 +938,14 @@ async def patch_non_null( """ @distributed_trace_async - async def patch_non_null(self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_non_null( + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DatetimeProperty or + ~typetest.property.nullable.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1000,12 +1014,12 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.DatetimeProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1031,11 +1045,14 @@ async def patch_null( """ @distributed_trace_async - async def patch_null(self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DatetimeProperty or + ~typetest.property.nullable.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1236,12 +1253,12 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.DurationProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1267,11 +1284,14 @@ async def patch_non_null( """ @distributed_trace_async - async def patch_non_null(self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_non_null( + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DurationProperty or + ~typetest.property.nullable.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1340,12 +1360,12 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.DurationProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1371,11 +1391,14 @@ async def patch_null( """ @distributed_trace_async - async def patch_null(self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DurationProperty or + ~typetest.property.nullable.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1580,12 +1603,12 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1612,12 +1635,13 @@ async def patch_non_null( @distributed_trace_async async def patch_non_null( - self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsByteProperty or + ~typetest.property.nullable.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1690,12 +1714,12 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1721,11 +1745,14 @@ async def patch_null( """ @distributed_trace_async - async def patch_null(self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsByteProperty or + ~typetest.property.nullable.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1932,12 +1959,16 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: _types.CollectionsModelProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1964,12 +1995,13 @@ async def patch_non_null( @distributed_trace_async async def patch_non_null( - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsModelProperty or + ~typetest.property.nullable.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2042,12 +2074,16 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: _types.CollectionsModelProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2073,11 +2109,14 @@ async def patch_null( """ @distributed_trace_async - async def patch_null(self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsModelProperty or + ~typetest.property.nullable.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2284,12 +2323,16 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: _types.CollectionsStringProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2316,13 +2359,13 @@ async def patch_non_null( @distributed_trace_async async def patch_non_null( - self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.nullable.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsStringProperty or + ~typetest.property.nullable.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2395,12 +2438,16 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: _types.CollectionsStringProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2426,12 +2473,14 @@ async def patch_null( """ @distributed_trace_async - async def patch_null(self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.nullable.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsStringProperty or + ~typetest.property.nullable.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/operations/_operations.py index 07aea4c88bdd..50241ad9ac07 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/operations/_operations.py @@ -27,12 +27,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import NullableClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -580,11 +579,13 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, body: _types.StringProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -611,12 +612,13 @@ def patch_non_null( @distributed_trace def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.StringProperty or + ~typetest.property.nullable.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -684,11 +686,13 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, body: _types.StringProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -713,12 +717,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- @distributed_trace def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.StringProperty or + ~typetest.property.nullable.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -918,11 +923,13 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, body: _types.BytesProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -949,12 +956,13 @@ def patch_non_null( @distributed_trace def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.BytesProperty or + ~typetest.property.nullable.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1022,11 +1030,13 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, body: _types.BytesProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1051,12 +1061,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- @distributed_trace def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.BytesProperty or + ~typetest.property.nullable.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1256,11 +1267,13 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, body: _types.DatetimeProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1287,12 +1300,13 @@ def patch_non_null( @distributed_trace def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DatetimeProperty or + ~typetest.property.nullable.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1360,11 +1374,13 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, body: _types.DatetimeProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1389,12 +1405,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- @distributed_trace def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DatetimeProperty or + ~typetest.property.nullable.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1594,11 +1611,13 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, body: _types.DurationProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1625,12 +1644,13 @@ def patch_non_null( @distributed_trace def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DurationProperty or + ~typetest.property.nullable.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1698,11 +1718,13 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, body: _types.DurationProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1727,12 +1749,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- @distributed_trace def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DurationProperty or + ~typetest.property.nullable.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1936,11 +1959,13 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1967,12 +1992,13 @@ def patch_non_null( @distributed_trace def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsByteProperty or + ~typetest.property.nullable.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2044,11 +2070,13 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2073,12 +2101,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- @distributed_trace def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsByteProperty or + ~typetest.property.nullable.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2284,11 +2313,17 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, + body: _types.CollectionsModelProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2315,12 +2350,13 @@ def patch_non_null( @distributed_trace def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsModelProperty or + ~typetest.property.nullable.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2392,11 +2428,17 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, + body: _types.CollectionsModelProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2421,12 +2463,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- @distributed_trace def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsModelProperty or + ~typetest.property.nullable.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2632,11 +2675,17 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, + body: _types.CollectionsStringProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2663,13 +2712,13 @@ def patch_non_null( @distributed_trace def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.nullable.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsStringProperty or + ~typetest.property.nullable.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2741,11 +2790,17 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, + body: _types.CollectionsStringProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2770,13 +2825,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- @distributed_trace def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.nullable.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsStringProperty or + ~typetest.property.nullable.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/types.py index 1dc2c39c037a..ec0c2a5631b9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-nullable/typetest/property/nullable/types.py @@ -6,7 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime from typing import Optional from typing_extensions import Required, TypedDict @@ -18,12 +17,12 @@ class BytesProperty(TypedDict, total=False): :ivar required_property: Required property. Required. :vartype required_property: str :ivar nullable_property: Property. Required. - :vartype nullable_property: bytes + :vartype nullable_property: str """ requiredProperty: Required[str] """Required property. Required.""" - nullableProperty: Required[Optional[bytes]] + nullableProperty: Required[Optional[str]] """Property. Required.""" @@ -33,12 +32,12 @@ class CollectionsByteProperty(TypedDict, total=False): :ivar required_property: Required property. Required. :vartype required_property: str :ivar nullable_property: Property. Required. - :vartype nullable_property: list[bytes] + :vartype nullable_property: list[str] """ requiredProperty: Required[str] """Required property. Required.""" - nullableProperty: Required[Optional[list[bytes]]] + nullableProperty: Required[Optional[list[str]]] """Property. Required.""" @@ -48,7 +47,7 @@ class CollectionsModelProperty(TypedDict, total=False): :ivar required_property: Required property. Required. :vartype required_property: str :ivar nullable_property: Property. Required. - :vartype nullable_property: list[~typetest.property.nullable.models.InnerModel] + :vartype nullable_property: list["InnerModel"] """ requiredProperty: Required[str] @@ -78,12 +77,12 @@ class DatetimeProperty(TypedDict, total=False): :ivar required_property: Required property. Required. :vartype required_property: str :ivar nullable_property: Property. Required. - :vartype nullable_property: ~datetime.datetime + :vartype nullable_property: str """ requiredProperty: Required[str] """Required property. Required.""" - nullableProperty: Required[Optional[datetime.datetime]] + nullableProperty: Required[Optional[str]] """Property. Required.""" @@ -93,12 +92,12 @@ class DurationProperty(TypedDict, total=False): :ivar required_property: Required property. Required. :vartype required_property: str :ivar nullable_property: Property. Required. - :vartype nullable_property: ~datetime.timedelta + :vartype nullable_property: str """ requiredProperty: Required[str] """Required property. Required.""" - nullableProperty: Required[Optional[datetime.timedelta]] + nullableProperty: Required[Optional[str]] """Property. Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/pyproject.toml index 47b00e2d54dd..82c5b8142121 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/operations/_operations.py index f31c8e79bddc..f1ca666804a0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -98,7 +98,6 @@ ) from .._configuration import OptionalClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -251,11 +250,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -279,11 +280,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringProperty or + ~typetest.property.optional.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -351,11 +355,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -379,11 +385,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringProperty or + ~typetest.property.optional.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -583,11 +592,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -611,11 +622,12 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all(self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BytesProperty or + ~typetest.property.optional.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -683,11 +695,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -711,11 +725,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BytesProperty or + ~typetest.property.optional.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -915,11 +932,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -943,11 +962,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DatetimeProperty or + ~typetest.property.optional.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1015,11 +1037,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1043,11 +1067,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DatetimeProperty or + ~typetest.property.optional.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1247,11 +1274,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1275,11 +1304,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DurationProperty or + ~typetest.property.optional.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1347,11 +1379,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1375,11 +1409,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DurationProperty or + ~typetest.property.optional.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1579,11 +1616,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.PlainDateProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainDateProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1607,11 +1646,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.PlainDateProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.PlainDateProperty, _types.PlainDateProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: PlainDateProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainDateProperty or JSON or IO[bytes] + :param body: Is either a PlainDateProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainDateProperty or + ~typetest.property.optional.types.PlainDateProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1679,11 +1721,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.PlainDateProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainDateProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1707,11 +1751,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.PlainDateProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.PlainDateProperty, _types.PlainDateProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: PlainDateProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainDateProperty or JSON or IO[bytes] + :param body: Is either a PlainDateProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainDateProperty or + ~typetest.property.optional.types.PlainDateProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1911,11 +1958,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.PlainTimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainTimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1939,11 +1988,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.PlainTimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.PlainTimeProperty, _types.PlainTimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: PlainTimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainTimeProperty or JSON or IO[bytes] + :param body: Is either a PlainTimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainTimeProperty or + ~typetest.property.optional.types.PlainTimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2011,11 +2063,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.PlainTimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainTimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2039,11 +2093,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.PlainTimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.PlainTimeProperty, _types.PlainTimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: PlainTimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainTimeProperty or JSON or IO[bytes] + :param body: Is either a PlainTimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainTimeProperty or + ~typetest.property.optional.types.PlainTimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2243,11 +2300,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2271,11 +2330,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsByteProperty or + ~typetest.property.optional.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2343,11 +2405,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2371,11 +2435,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsByteProperty or + ~typetest.property.optional.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2577,11 +2644,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2605,11 +2674,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsModelProperty or + ~typetest.property.optional.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2677,11 +2749,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2705,11 +2779,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsModelProperty or + ~typetest.property.optional.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2909,11 +2986,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2937,11 +3016,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringLiteralProperty or JSON or IO[bytes] + :param body: Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringLiteralProperty or + ~typetest.property.optional.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3009,11 +3091,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3037,11 +3121,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringLiteralProperty or JSON or IO[bytes] + :param body: Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringLiteralProperty or + ~typetest.property.optional.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3241,11 +3328,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3269,11 +3358,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.IntLiteralProperty or JSON or IO[bytes] + :param body: Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.IntLiteralProperty or + ~typetest.property.optional.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3341,11 +3433,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3369,11 +3463,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.IntLiteralProperty or JSON or IO[bytes] + :param body: Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.IntLiteralProperty or + ~typetest.property.optional.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3573,11 +3670,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3601,11 +3700,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.FloatLiteralProperty or + ~typetest.property.optional.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3673,11 +3775,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3701,11 +3805,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.FloatLiteralProperty or + ~typetest.property.optional.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3905,11 +4012,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3933,11 +4042,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BooleanLiteralProperty or + ~typetest.property.optional.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4005,11 +4117,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4033,11 +4147,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BooleanLiteralProperty or + ~typetest.property.optional.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4239,11 +4356,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4267,12 +4386,16 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or + ~typetest.property.optional.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4340,11 +4463,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4369,13 +4494,15 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application @distributed_trace_async async def put_default( - self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or + ~typetest.property.optional.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4575,11 +4702,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4603,11 +4732,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or + ~typetest.property.optional.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4675,11 +4807,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4703,11 +4837,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or + ~typetest.property.optional.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4909,11 +5046,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4937,12 +5076,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or + ~typetest.property.optional.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5010,11 +5151,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5038,12 +5181,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ @distributed_trace_async - async def put_default(self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or + ~typetest.property.optional.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5245,11 +5390,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.RequiredAndOptionalProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.RequiredAndOptionalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5273,12 +5420,16 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso """ @distributed_trace_async - async def put_all(self, body: Union[_models.RequiredAndOptionalProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, + body: Union[_models.RequiredAndOptionalProperty, _types.RequiredAndOptionalProperty, IO[bytes]], + **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: RequiredAndOptionalProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or JSON or IO[bytes] + :param body: Is either a RequiredAndOptionalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or + ~typetest.property.optional.types.RequiredAndOptionalProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5346,11 +5497,13 @@ async def put_required_only( """ @overload - async def put_required_only(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_required_only( + self, body: _types.RequiredAndOptionalProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with only required properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.RequiredAndOptionalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5377,13 +5530,15 @@ async def put_required_only( @distributed_trace_async async def put_required_only( - self, body: Union[_models.RequiredAndOptionalProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.RequiredAndOptionalProperty, _types.RequiredAndOptionalProperty, IO[bytes]], + **kwargs: Any ) -> None: """Put a body with only required properties. - :param body: Is one of the following types: RequiredAndOptionalProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or JSON or IO[bytes] + :param body: Is either a RequiredAndOptionalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or + ~typetest.property.optional.types.RequiredAndOptionalProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/operations/_operations.py index 69aea42ed165..5cae6880ec4f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/operations/_operations.py @@ -27,12 +27,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import OptionalClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -1086,11 +1085,11 @@ def put_all(self, body: _models.StringProperty, *, content_type: str = "applicat """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1115,12 +1114,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringProperty or + ~typetest.property.optional.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1188,11 +1188,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1217,12 +1219,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringProperty or + ~typetest.property.optional.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1420,11 +1423,11 @@ def put_all(self, body: _models.BytesProperty, *, content_type: str = "applicati """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1449,12 +1452,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BytesProperty or + ~typetest.property.optional.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1522,11 +1526,11 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default(self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1551,12 +1555,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BytesProperty or + ~typetest.property.optional.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1754,11 +1759,11 @@ def put_all(self, body: _models.DatetimeProperty, *, content_type: str = "applic """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1783,12 +1788,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DatetimeProperty or + ~typetest.property.optional.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1856,11 +1862,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1885,12 +1893,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DatetimeProperty or + ~typetest.property.optional.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2088,11 +2097,11 @@ def put_all(self, body: _models.DurationProperty, *, content_type: str = "applic """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2117,12 +2126,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DurationProperty or + ~typetest.property.optional.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2190,11 +2200,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2219,12 +2231,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DurationProperty or + ~typetest.property.optional.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2424,11 +2437,11 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.PlainDateProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainDateProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2453,12 +2466,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PlainDateProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.PlainDateProperty, _types.PlainDateProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: PlainDateProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainDateProperty or JSON or IO[bytes] + :param body: Is either a PlainDateProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainDateProperty or + ~typetest.property.optional.types.PlainDateProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2526,11 +2540,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.PlainDateProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainDateProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2555,12 +2571,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PlainDateProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.PlainDateProperty, _types.PlainDateProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: PlainDateProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainDateProperty or JSON or IO[bytes] + :param body: Is either a PlainDateProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainDateProperty or + ~typetest.property.optional.types.PlainDateProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2760,11 +2777,11 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.PlainTimeProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainTimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2789,12 +2806,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PlainTimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.PlainTimeProperty, _types.PlainTimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: PlainTimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainTimeProperty or JSON or IO[bytes] + :param body: Is either a PlainTimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainTimeProperty or + ~typetest.property.optional.types.PlainTimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2862,11 +2880,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.PlainTimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainTimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2891,12 +2911,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PlainTimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.PlainTimeProperty, _types.PlainTimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: PlainTimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainTimeProperty or JSON or IO[bytes] + :param body: Is either a PlainTimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainTimeProperty or + ~typetest.property.optional.types.PlainTimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3096,11 +3117,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3125,12 +3148,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsByteProperty or + ~typetest.property.optional.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3198,11 +3222,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3227,12 +3253,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsByteProperty or + ~typetest.property.optional.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3434,11 +3461,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3463,12 +3492,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsModelProperty or + ~typetest.property.optional.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3536,11 +3566,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3565,12 +3597,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsModelProperty or + ~typetest.property.optional.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3770,11 +3803,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3799,12 +3834,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringLiteralProperty or JSON or IO[bytes] + :param body: Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringLiteralProperty or + ~typetest.property.optional.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3872,11 +3908,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3901,12 +3939,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringLiteralProperty or JSON or IO[bytes] + :param body: Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringLiteralProperty or + ~typetest.property.optional.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4106,11 +4145,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4135,12 +4176,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.IntLiteralProperty or JSON or IO[bytes] + :param body: Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.IntLiteralProperty or + ~typetest.property.optional.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4208,11 +4250,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4237,12 +4281,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.IntLiteralProperty or JSON or IO[bytes] + :param body: Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.IntLiteralProperty or + ~typetest.property.optional.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4442,11 +4487,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4471,12 +4518,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.FloatLiteralProperty or + ~typetest.property.optional.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4544,11 +4592,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4573,12 +4623,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.FloatLiteralProperty or + ~typetest.property.optional.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4778,11 +4829,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4807,12 +4860,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BooleanLiteralProperty or + ~typetest.property.optional.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4880,11 +4934,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4909,12 +4965,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BooleanLiteralProperty or + ~typetest.property.optional.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5116,11 +5173,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5145,13 +5204,15 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any, ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or + ~typetest.property.optional.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5219,11 +5280,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5248,13 +5311,15 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any, ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or + ~typetest.property.optional.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5454,11 +5519,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5483,12 +5550,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or + ~typetest.property.optional.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5556,11 +5624,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5585,12 +5655,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or + ~typetest.property.optional.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5792,11 +5863,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5821,13 +5894,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or + ~typetest.property.optional.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5895,11 +5968,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5924,13 +5999,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" @distributed_trace def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or + ~typetest.property.optional.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6132,11 +6207,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.RequiredAndOptionalProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.RequiredAndOptionalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -6161,13 +6238,15 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** @distributed_trace def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.RequiredAndOptionalProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.RequiredAndOptionalProperty, _types.RequiredAndOptionalProperty, IO[bytes]], + **kwargs: Any, ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: RequiredAndOptionalProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or JSON or IO[bytes] + :param body: Is either a RequiredAndOptionalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or + ~typetest.property.optional.types.RequiredAndOptionalProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6235,11 +6314,13 @@ def put_required_only( """ @overload - def put_required_only(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_required_only( + self, body: _types.RequiredAndOptionalProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with only required properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.RequiredAndOptionalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -6264,13 +6345,15 @@ def put_required_only(self, body: IO[bytes], *, content_type: str = "application @distributed_trace def put_required_only( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.RequiredAndOptionalProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.RequiredAndOptionalProperty, _types.RequiredAndOptionalProperty, IO[bytes]], + **kwargs: Any, ) -> None: """Put a body with only required properties. - :param body: Is one of the following types: RequiredAndOptionalProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or JSON or IO[bytes] + :param body: Is either a RequiredAndOptionalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or + ~typetest.property.optional.types.RequiredAndOptionalProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/types.py index fa53cab3de11..89bfd66cf50d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-optional/typetest/property/optional/types.py @@ -6,7 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime from typing import Literal from typing_extensions import Required, TypedDict @@ -15,7 +14,7 @@ class BooleanLiteralProperty(TypedDict, total=False): """Model with boolean literal property. :ivar property: Property. Default value is True. - :vartype property: bool + :vartype property: Literal[True] """ property: Literal[True] @@ -27,10 +26,10 @@ class BytesProperty(TypedDict, total=False): are looking for. :ivar property: Property. - :vartype property: bytes + :vartype property: str """ - property: bytes + property: str """Property.""" @@ -38,10 +37,10 @@ class CollectionsByteProperty(TypedDict, total=False): """Model with collection bytes properties. :ivar property: Property. - :vartype property: list[bytes] + :vartype property: list[str] """ - property: list[bytes] + property: list[str] """Property.""" @@ -49,7 +48,7 @@ class CollectionsModelProperty(TypedDict, total=False): """Model with collection models properties. :ivar property: Property. - :vartype property: list[~typetest.property.optional.models.StringProperty] + :vartype property: list["StringProperty"] """ property: list["StringProperty"] @@ -60,10 +59,10 @@ class DatetimeProperty(TypedDict, total=False): """Model with a datetime property. :ivar property: Property. - :vartype property: ~datetime.datetime + :vartype property: str """ - property: datetime.datetime + property: str """Property.""" @@ -71,10 +70,10 @@ class DurationProperty(TypedDict, total=False): """Model with a duration property. :ivar property: Property. - :vartype property: ~datetime.timedelta + :vartype property: str """ - property: datetime.timedelta + property: str """Property.""" @@ -93,7 +92,7 @@ class IntLiteralProperty(TypedDict, total=False): """Model with int literal property. :ivar property: Property. Default value is 1. - :vartype property: int + :vartype property: Literal[1] """ property: Literal[1] @@ -104,10 +103,10 @@ class PlainDateProperty(TypedDict, total=False): """Model with a plainDate property. :ivar property: Property. - :vartype property: ~datetime.date + :vartype property: str """ - property: datetime.date + property: str """Property.""" @@ -115,10 +114,10 @@ class PlainTimeProperty(TypedDict, total=False): """Model with a plainTime property. :ivar property: Property. - :vartype property: ~datetime.time + :vartype property: str """ - property: datetime.time + property: str """Property.""" @@ -141,7 +140,7 @@ class StringLiteralProperty(TypedDict, total=False): """Model with string literal property. :ivar property: Property. Default value is "hello". - :vartype property: str + :vartype property: Literal["hello"] """ property: Literal["hello"] @@ -164,7 +163,7 @@ class UnionFloatLiteralProperty(TypedDict, total=False): """Model with union of float literal property. :ivar property: Property. Is one of the following types: float - :vartype property: float or float + :vartype property: float """ property: float @@ -175,7 +174,7 @@ class UnionIntLiteralProperty(TypedDict, total=False): """Model with union of int literal property. :ivar property: Property. Is either a Literal[1] type or a Literal[2] type. - :vartype property: int or int + :vartype property: Literal[1, 2] """ property: Literal[1, 2] @@ -186,7 +185,7 @@ class UnionStringLiteralProperty(TypedDict, total=False): """Model with union of string literal property. :ivar property: Property. Is either a Literal["hello"] type or a Literal["world"] type. - :vartype property: str or str + :vartype property: Literal["hello", "world"] """ property: Literal["hello", "world"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/pyproject.toml index 4692d5ef5085..8423e1318438 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_operations.py index 8b64e37f8f24..b59e96b2bd1a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -92,7 +92,6 @@ ) from .._configuration import ValueTypesClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -188,11 +187,11 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.BooleanProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BooleanProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -216,11 +215,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.BooleanProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.BooleanProperty, _types.BooleanProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: BooleanProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.BooleanProperty or JSON or IO[bytes] + :param body: body. Is either a BooleanProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BooleanProperty or + ~typetest.property.valuetypes.types.BooleanProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -361,11 +361,11 @@ async def put(self, body: _models.StringProperty, *, content_type: str = "applic """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -389,11 +389,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.StringProperty or JSON or IO[bytes] + :param body: body. Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.StringProperty or + ~typetest.property.valuetypes.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -534,11 +535,11 @@ async def put(self, body: _models.BytesProperty, *, content_type: str = "applica """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -562,11 +563,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.BytesProperty or JSON or IO[bytes] + :param body: body. Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BytesProperty or + ~typetest.property.valuetypes.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -707,11 +709,11 @@ async def put(self, body: _models.IntProperty, *, content_type: str = "applicati """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.IntProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.IntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -735,11 +737,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.IntProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.IntProperty, _types.IntProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: IntProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.IntProperty or JSON or IO[bytes] + :param body: body. Is either a IntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.IntProperty or + ~typetest.property.valuetypes.types.IntProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -880,11 +883,11 @@ async def put(self, body: _models.FloatProperty, *, content_type: str = "applica """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.FloatProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.FloatProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -908,11 +911,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.FloatProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.FloatProperty, _types.FloatProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: FloatProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.FloatProperty or JSON or IO[bytes] + :param body: body. Is either a FloatProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.FloatProperty or + ~typetest.property.valuetypes.types.FloatProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1055,11 +1059,11 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.DecimalProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DecimalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1083,11 +1087,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DecimalProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.DecimalProperty, _types.DecimalProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: DecimalProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DecimalProperty or JSON or IO[bytes] + :param body: body. Is either a DecimalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DecimalProperty or + ~typetest.property.valuetypes.types.DecimalProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1230,11 +1235,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.Decimal128Property, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.Decimal128Property :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1258,11 +1265,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.Decimal128Property, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.Decimal128Property, _types.Decimal128Property, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: Decimal128Property, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.Decimal128Property or JSON or IO[bytes] + :param body: body. Is either a Decimal128Property type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.Decimal128Property or + ~typetest.property.valuetypes.types.Decimal128Property or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1405,11 +1415,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1433,11 +1445,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DatetimeProperty or JSON or IO[bytes] + :param body: body. Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DatetimeProperty or + ~typetest.property.valuetypes.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1580,11 +1595,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1608,11 +1625,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DurationProperty or JSON or IO[bytes] + :param body: body. Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DurationProperty or + ~typetest.property.valuetypes.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1753,11 +1773,11 @@ async def put(self, body: _models.EnumProperty, *, content_type: str = "applicat """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.EnumProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.EnumProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1781,11 +1801,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.EnumProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.EnumProperty, _types.EnumProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: EnumProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.EnumProperty or JSON or IO[bytes] + :param body: body. Is either a EnumProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.EnumProperty or + ~typetest.property.valuetypes.types.EnumProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1928,11 +1949,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.ExtensibleEnumProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.ExtensibleEnumProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1956,12 +1979,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.ExtensibleEnumProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.ExtensibleEnumProperty, _types.ExtensibleEnumProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtensibleEnumProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.ExtensibleEnumProperty or JSON or IO[bytes] + :param body: body. Is either a ExtensibleEnumProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.ExtensibleEnumProperty or + ~typetest.property.valuetypes.types.ExtensibleEnumProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2102,11 +2127,11 @@ async def put(self, body: _models.ModelProperty, *, content_type: str = "applica """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.ModelProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.ModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2130,11 +2155,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.ModelProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.ModelProperty, _types.ModelProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: ModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.ModelProperty or JSON or IO[bytes] + :param body: body. Is either a ModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.ModelProperty or + ~typetest.property.valuetypes.types.ModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2278,11 +2304,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.CollectionsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2306,12 +2334,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsStringProperty or + ~typetest.property.valuetypes.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2454,11 +2484,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.CollectionsIntProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsIntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2482,12 +2514,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.CollectionsIntProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.CollectionsIntProperty, _types.CollectionsIntProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsIntProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsIntProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsIntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsIntProperty or + ~typetest.property.valuetypes.types.CollectionsIntProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2631,11 +2665,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2659,12 +2695,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsModelProperty or + ~typetest.property.valuetypes.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2808,11 +2846,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DictionaryStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DictionaryStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2836,12 +2876,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.DictionaryStringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.DictionaryStringProperty, _types.DictionaryStringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DictionaryStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.DictionaryStringProperty or JSON or IO[bytes] + :param body: body. Is either a DictionaryStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DictionaryStringProperty or + ~typetest.property.valuetypes.types.DictionaryStringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2982,11 +3024,11 @@ async def put(self, body: _models.NeverProperty, *, content_type: str = "applica """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.NeverProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.NeverProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3010,11 +3052,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.NeverProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.NeverProperty, _types.NeverProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: NeverProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.NeverProperty or JSON or IO[bytes] + :param body: body. Is either a NeverProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.NeverProperty or + ~typetest.property.valuetypes.types.NeverProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3157,11 +3200,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnknownStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3185,12 +3230,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.UnknownStringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnknownStringProperty, _types.UnknownStringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownStringProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownStringProperty or + ~typetest.property.valuetypes.types.UnknownStringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3333,11 +3380,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnknownIntProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownIntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3361,11 +3410,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.UnknownIntProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnknownIntProperty, _types.UnknownIntProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownIntProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.UnknownIntProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownIntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownIntProperty or + ~typetest.property.valuetypes.types.UnknownIntProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3508,11 +3560,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnknownDictProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownDictProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3536,12 +3590,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.UnknownDictProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnknownDictProperty, _types.UnknownDictProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownDictProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownDictProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownDictProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownDictProperty or + ~typetest.property.valuetypes.types.UnknownDictProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3684,11 +3740,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnknownArrayProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3712,12 +3770,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.UnknownArrayProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnknownArrayProperty, _types.UnknownArrayProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownArrayProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownArrayProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownArrayProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownArrayProperty or + ~typetest.property.valuetypes.types.UnknownArrayProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3860,11 +3920,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3888,12 +3950,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: StringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.StringLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.StringLiteralProperty or + ~typetest.property.valuetypes.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4036,11 +4100,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4064,11 +4130,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.IntLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.IntLiteralProperty or + ~typetest.property.valuetypes.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4211,11 +4280,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4239,12 +4310,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.FloatLiteralProperty or + ~typetest.property.valuetypes.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4387,11 +4460,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4415,12 +4490,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BooleanLiteralProperty or + ~typetest.property.valuetypes.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4564,11 +4641,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4592,13 +4671,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionStringLiteralProperty or JSON or - IO[bytes] + :param body: body. Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionStringLiteralProperty or + ~typetest.property.valuetypes.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4741,11 +4823,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4769,12 +4853,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionIntLiteralProperty or + ~typetest.property.valuetypes.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4918,11 +5004,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4946,12 +5034,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionFloatLiteralProperty or + ~typetest.property.valuetypes.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5094,11 +5184,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnionEnumValueProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionEnumValueProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5122,12 +5214,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def put(self, body: Union[_models.UnionEnumValueProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnionEnumValueProperty, _types.UnionEnumValueProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionEnumValueProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionEnumValueProperty or JSON or IO[bytes] + :param body: body. Is either a UnionEnumValueProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionEnumValueProperty or + ~typetest.property.valuetypes.types.UnionEnumValueProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/operations/_operations.py index 0a250dade4f8..7119675f3d1b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/operations/_operations.py @@ -27,12 +27,11 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import ValueTypesClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -941,11 +940,11 @@ def put(self, body: _models.BooleanProperty, *, content_type: str = "application """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.BooleanProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BooleanProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -970,12 +969,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BooleanProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BooleanProperty, _types.BooleanProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: BooleanProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.BooleanProperty or JSON or IO[bytes] + :param body: body. Is either a BooleanProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BooleanProperty or + ~typetest.property.valuetypes.types.BooleanProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1116,11 +1116,11 @@ def put(self, body: _models.StringProperty, *, content_type: str = "application/ """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1145,12 +1145,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.StringProperty or JSON or IO[bytes] + :param body: body. Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.StringProperty or + ~typetest.property.valuetypes.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1291,11 +1292,11 @@ def put(self, body: _models.BytesProperty, *, content_type: str = "application/j """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1320,12 +1321,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.BytesProperty or JSON or IO[bytes] + :param body: body. Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BytesProperty or + ~typetest.property.valuetypes.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1466,11 +1468,11 @@ def put(self, body: _models.IntProperty, *, content_type: str = "application/jso """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.IntProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.IntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1495,12 +1497,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IntProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.IntProperty, _types.IntProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: IntProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.IntProperty or JSON or IO[bytes] + :param body: body. Is either a IntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.IntProperty or + ~typetest.property.valuetypes.types.IntProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1641,11 +1644,11 @@ def put(self, body: _models.FloatProperty, *, content_type: str = "application/j """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.FloatProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.FloatProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1670,12 +1673,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FloatProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.FloatProperty, _types.FloatProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: FloatProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.FloatProperty or JSON or IO[bytes] + :param body: body. Is either a FloatProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.FloatProperty or + ~typetest.property.valuetypes.types.FloatProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1816,11 +1820,11 @@ def put(self, body: _models.DecimalProperty, *, content_type: str = "application """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.DecimalProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DecimalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1845,12 +1849,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DecimalProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DecimalProperty, _types.DecimalProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: DecimalProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DecimalProperty or JSON or IO[bytes] + :param body: body. Is either a DecimalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DecimalProperty or + ~typetest.property.valuetypes.types.DecimalProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1991,11 +1996,11 @@ def put(self, body: _models.Decimal128Property, *, content_type: str = "applicat """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.Decimal128Property, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.Decimal128Property :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2020,12 +2025,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.Decimal128Property, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.Decimal128Property, _types.Decimal128Property, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: Decimal128Property, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.Decimal128Property or JSON or IO[bytes] + :param body: body. Is either a Decimal128Property type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.Decimal128Property or + ~typetest.property.valuetypes.types.Decimal128Property or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2166,11 +2172,11 @@ def put(self, body: _models.DatetimeProperty, *, content_type: str = "applicatio """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2195,12 +2201,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DatetimeProperty or JSON or IO[bytes] + :param body: body. Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DatetimeProperty or + ~typetest.property.valuetypes.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2341,11 +2348,11 @@ def put(self, body: _models.DurationProperty, *, content_type: str = "applicatio """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2370,12 +2377,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DurationProperty or JSON or IO[bytes] + :param body: body. Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DurationProperty or + ~typetest.property.valuetypes.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2516,11 +2524,11 @@ def put(self, body: _models.EnumProperty, *, content_type: str = "application/js """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.EnumProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.EnumProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2545,12 +2553,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.EnumProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.EnumProperty, _types.EnumProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: EnumProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.EnumProperty or JSON or IO[bytes] + :param body: body. Is either a EnumProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.EnumProperty or + ~typetest.property.valuetypes.types.EnumProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2693,11 +2702,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.ExtensibleEnumProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.ExtensibleEnumProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2722,13 +2733,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtensibleEnumProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ExtensibleEnumProperty, _types.ExtensibleEnumProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtensibleEnumProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.ExtensibleEnumProperty or JSON or IO[bytes] + :param body: body. Is either a ExtensibleEnumProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.ExtensibleEnumProperty or + ~typetest.property.valuetypes.types.ExtensibleEnumProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2869,11 +2880,11 @@ def put(self, body: _models.ModelProperty, *, content_type: str = "application/j """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.ModelProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.ModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2898,12 +2909,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ModelProperty, _types.ModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: ModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.ModelProperty or JSON or IO[bytes] + :param body: body. Is either a ModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.ModelProperty or + ~typetest.property.valuetypes.types.ModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3047,11 +3059,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.CollectionsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3076,13 +3090,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsStringProperty or + ~typetest.property.valuetypes.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3225,11 +3239,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.CollectionsIntProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsIntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3254,13 +3270,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsIntProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsIntProperty, _types.CollectionsIntProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsIntProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsIntProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsIntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsIntProperty or + ~typetest.property.valuetypes.types.CollectionsIntProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3404,11 +3420,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3433,13 +3451,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsModelProperty or + ~typetest.property.valuetypes.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3583,11 +3601,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DictionaryStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DictionaryStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3612,13 +3632,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DictionaryStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DictionaryStringProperty, _types.DictionaryStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: DictionaryStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.DictionaryStringProperty or JSON or IO[bytes] + :param body: body. Is either a DictionaryStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DictionaryStringProperty or + ~typetest.property.valuetypes.types.DictionaryStringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3759,11 +3779,11 @@ def put(self, body: _models.NeverProperty, *, content_type: str = "application/j """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.NeverProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.NeverProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3788,12 +3808,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.NeverProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.NeverProperty, _types.NeverProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: NeverProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.NeverProperty or JSON or IO[bytes] + :param body: body. Is either a NeverProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.NeverProperty or + ~typetest.property.valuetypes.types.NeverProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3936,11 +3957,11 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.UnknownStringProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3965,13 +3986,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnknownStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnknownStringProperty, _types.UnknownStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownStringProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownStringProperty or + ~typetest.property.valuetypes.types.UnknownStringProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4112,11 +4133,11 @@ def put(self, body: _models.UnknownIntProperty, *, content_type: str = "applicat """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.UnknownIntProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownIntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4141,12 +4162,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnknownIntProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnknownIntProperty, _types.UnknownIntProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownIntProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.UnknownIntProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownIntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownIntProperty or + ~typetest.property.valuetypes.types.UnknownIntProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4287,11 +4309,11 @@ def put(self, body: _models.UnknownDictProperty, *, content_type: str = "applica """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.UnknownDictProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownDictProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4316,13 +4338,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnknownDictProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnknownDictProperty, _types.UnknownDictProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownDictProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownDictProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownDictProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownDictProperty or + ~typetest.property.valuetypes.types.UnknownDictProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4463,11 +4485,11 @@ def put(self, body: _models.UnknownArrayProperty, *, content_type: str = "applic """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.UnknownArrayProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4492,13 +4514,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnknownArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnknownArrayProperty, _types.UnknownArrayProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownArrayProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownArrayProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownArrayProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownArrayProperty or + ~typetest.property.valuetypes.types.UnknownArrayProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4641,11 +4663,11 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4670,13 +4692,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: StringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.StringLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.StringLiteralProperty or + ~typetest.property.valuetypes.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4817,11 +4839,11 @@ def put(self, body: _models.IntLiteralProperty, *, content_type: str = "applicat """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4846,12 +4868,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.IntLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.IntLiteralProperty or + ~typetest.property.valuetypes.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4992,11 +5015,11 @@ def put(self, body: _models.FloatLiteralProperty, *, content_type: str = "applic """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5021,13 +5044,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.FloatLiteralProperty or + ~typetest.property.valuetypes.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5170,11 +5193,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5199,13 +5224,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BooleanLiteralProperty or + ~typetest.property.valuetypes.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5349,11 +5374,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5378,14 +5405,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionStringLiteralProperty or JSON or - IO[bytes] + :param body: body. Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionStringLiteralProperty or + ~typetest.property.valuetypes.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5528,11 +5556,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5557,13 +5587,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionIntLiteralProperty or + ~typetest.property.valuetypes.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5707,11 +5737,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5736,13 +5768,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionFloatLiteralProperty or + ~typetest.property.valuetypes.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5885,11 +5917,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.UnionEnumValueProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionEnumValueProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5914,13 +5948,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar @distributed_trace def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionEnumValueProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionEnumValueProperty, _types.UnionEnumValueProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionEnumValueProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionEnumValueProperty or JSON or IO[bytes] + :param body: body. Is either a UnionEnumValueProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionEnumValueProperty or + ~typetest.property.valuetypes.types.UnionEnumValueProperty or IO[bytes] :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/types.py index 3dd8ca24108c..5aa50b2435e6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-property-valuetypes/typetest/property/valuetypes/types.py @@ -6,8 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -import decimal from typing import Any, Literal, TYPE_CHECKING, Union from typing_extensions import Required, TypedDict @@ -21,7 +19,7 @@ class BooleanLiteralProperty(TypedDict, total=False): """Model with a boolean literal property. :ivar property: Property. Required. Default value is True. - :vartype property: bool + :vartype property: Literal[True] """ property: Required[Literal[True]] @@ -43,10 +41,10 @@ class BytesProperty(TypedDict, total=False): """Model with a bytes property. :ivar property: Property. Required. - :vartype property: bytes + :vartype property: str """ - property: Required[bytes] + property: Required[str] """Property. Required.""" @@ -65,7 +63,7 @@ class CollectionsModelProperty(TypedDict, total=False): """Model with collection model properties. :ivar property: Property. Required. - :vartype property: list[~typetest.property.valuetypes.models.InnerModel] + :vartype property: list["InnerModel"] """ property: Required[list["InnerModel"]] @@ -87,10 +85,10 @@ class DatetimeProperty(TypedDict, total=False): """Model with a datetime property. :ivar property: Property. Required. - :vartype property: ~datetime.datetime + :vartype property: str """ - property: Required[datetime.datetime] + property: Required[str] """Property. Required.""" @@ -98,10 +96,10 @@ class Decimal128Property(TypedDict, total=False): """Model with a decimal128 property. :ivar property: Property. Required. - :vartype property: ~decimal.Decimal + :vartype property: float """ - property: Required[decimal.Decimal] + property: Required[float] """Property. Required.""" @@ -109,10 +107,10 @@ class DecimalProperty(TypedDict, total=False): """Model with a decimal property. :ivar property: Property. Required. - :vartype property: ~decimal.Decimal + :vartype property: float """ - property: Required[decimal.Decimal] + property: Required[float] """Property. Required.""" @@ -131,10 +129,10 @@ class DurationProperty(TypedDict, total=False): """Model with a duration property. :ivar property: Property. Required. - :vartype property: ~datetime.timedelta + :vartype property: str """ - property: Required[datetime.timedelta] + property: Required[str] """Property. Required.""" @@ -142,7 +140,7 @@ class EnumProperty(TypedDict, total=False): """Model with enum properties. :ivar property: Property. Required. Known values are: "ValueOne" and "ValueTwo". - :vartype property: str or ~typetest.property.valuetypes.models.FixedInnerEnum + :vartype property: Union[str, "FixedInnerEnum"] """ property: Required[Union[str, "FixedInnerEnum"]] @@ -153,7 +151,7 @@ class ExtensibleEnumProperty(TypedDict, total=False): """Model with extensible enum properties. :ivar property: Property. Required. Known values are: "ValueOne" and "ValueTwo". - :vartype property: str or ~typetest.property.valuetypes.models.InnerEnum + :vartype property: Union[str, "InnerEnum"] """ property: Required[Union[str, "InnerEnum"]] @@ -197,7 +195,7 @@ class IntLiteralProperty(TypedDict, total=False): """Model with a int literal property. :ivar property: Property. Required. Default value is 42. - :vartype property: int + :vartype property: Literal[42] """ property: Required[Literal[42]] @@ -219,7 +217,7 @@ class ModelProperty(TypedDict, total=False): """Model with model properties. :ivar property: Property. Required. - :vartype property: ~typetest.property.valuetypes.models.InnerModel + :vartype property: "InnerModel" """ property: Required["InnerModel"] @@ -234,7 +232,7 @@ class StringLiteralProperty(TypedDict, total=False): """Model with a string literal property. :ivar property: Property. Required. Default value is "hello". - :vartype property: str + :vartype property: Literal["hello"] """ property: Required[Literal["hello"]] @@ -257,7 +255,7 @@ class UnionEnumValueProperty(TypedDict, total=False): are looking for. :ivar property: Property. Required. ENUM_VALUE2. - :vartype property: str or ~typetest.property.valuetypes.models.ENUM_VALUE2 + :vartype property: Literal[ExtendedEnum.ENUM_VALUE2] """ property: Required[Literal[ExtendedEnum.ENUM_VALUE2]] @@ -268,7 +266,7 @@ class UnionFloatLiteralProperty(TypedDict, total=False): """Model with a union of float literal as property. :ivar property: Property. Required. Is one of the following types: float - :vartype property: float or float + :vartype property: float """ property: Required[float] @@ -279,7 +277,7 @@ class UnionIntLiteralProperty(TypedDict, total=False): """Model with a union of int literal as property. :ivar property: Property. Required. Is either a Literal[42] type or a Literal[43] type. - :vartype property: int or int + :vartype property: Literal[42, 43] """ property: Required[Literal[42, 43]] @@ -291,7 +289,7 @@ class UnionStringLiteralProperty(TypedDict, total=False): :ivar property: Property. Required. Is either a Literal["hello"] type or a Literal["world"] type. - :vartype property: str or str + :vartype property: Literal["hello", "world"] """ property: Required[Literal["hello", "world"]] @@ -302,7 +300,7 @@ class UnknownArrayProperty(TypedDict, total=False): """Model with a property unknown, and the data is an array. :ivar property: Property. Required. - :vartype property: any + :vartype property: Any """ property: Required[Any] @@ -313,7 +311,7 @@ class UnknownDictProperty(TypedDict, total=False): """Model with a property unknown, and the data is a dictionnary. :ivar property: Property. Required. - :vartype property: any + :vartype property: Any """ property: Required[Any] @@ -324,7 +322,7 @@ class UnknownIntProperty(TypedDict, total=False): """Model with a property unknown, and the data is a int32. :ivar property: Property. Required. - :vartype property: any + :vartype property: Any """ property: Required[Any] @@ -335,7 +333,7 @@ class UnknownStringProperty(TypedDict, total=False): """Model with a property unknown, and the data is a string. :ivar property: Property. Required. - :vartype property: any + :vartype property: Any """ property: Required[Any] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/pyproject.toml index 18f7d4cb4d55..d7f5fa21214f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-scalar/typetest/scalar/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/pyproject.toml index ed91415e85dc..93fdb2047ce1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/operations/_operations.py index 1775e089b943..5b8ef3708208 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -152,11 +152,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -181,12 +181,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Literal["a", "b", "c"] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest, IO[bytes]] = _Unset, + *, + prop: Literal["a", "b", "c"] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest or IO[bytes] :keyword prop: Is one of the following types: Literal["a"], Literal["b"], Literal["c"] Required. :paramtype prop: str or str or str @@ -337,11 +341,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest1, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest1 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -367,15 +371,15 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def send( self, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SendRequest1, IO[bytes]] = _Unset, *, prop: Union[Literal["b"], Literal["c"], str] = _Unset, **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest1, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest1 or IO[bytes] :keyword prop: Is one of the following types: Literal["b"], Literal["c"], str Required. :paramtype prop: str or str or str :return: None @@ -529,11 +533,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest2, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -559,15 +563,15 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def send( self, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SendRequest2, IO[bytes]] = _Unset, *, prop: Union[str, _models.StringExtensibleNamedUnion] = _Unset, **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest2, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest2 or IO[bytes] :keyword prop: Known values are: "b" and "c". Required. :paramtype prop: str or ~typetest.union.models.StringExtensibleNamedUnion :return: None @@ -715,11 +719,11 @@ async def send(self, *, prop: Literal[1, 2, 3], content_type: str = "application """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest3, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -744,12 +748,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Literal[1, 2, 3] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest3, IO[bytes]] = _Unset, + *, + prop: Literal[1, 2, 3] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest3, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest3 or IO[bytes] :keyword prop: Is one of the following types: Literal[1], Literal[2], Literal[3] Required. :paramtype prop: int or int or int :return: None @@ -897,11 +905,11 @@ async def send(self, *, prop: float, content_type: str = "application/json", **k """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest4, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest4 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -925,11 +933,13 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", """ @distributed_trace_async - async def send(self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: float = _Unset, **kwargs: Any) -> None: + async def send( + self, body: Union[JSON, _types.SendRequest4, IO[bytes]] = _Unset, *, prop: float = _Unset, **kwargs: Any + ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest4, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest4 or IO[bytes] :keyword prop: Is one of the following types: float Required. :paramtype prop: float or float or float :return: None @@ -1079,11 +1089,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest5, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest5 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1108,12 +1118,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Union[_models.Cat, _models.Dog] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest5, IO[bytes]] = _Unset, + *, + prop: Union[_models.Cat, _models.Dog] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest5, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest5 or IO[bytes] :keyword prop: Is either a Cat type or a Dog type. Required. :paramtype prop: ~typetest.union.models.Cat or ~typetest.union.models.Dog :return: None @@ -1263,11 +1277,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest6, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest6 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1292,12 +1306,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.EnumsOnlyCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest6, IO[bytes]] = _Unset, + *, + prop: _models.EnumsOnlyCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest6, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest6 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.EnumsOnlyCases :return: None @@ -1447,11 +1465,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest7, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest7 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1476,12 +1494,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.StringAndArrayCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest7, IO[bytes]] = _Unset, + *, + prop: _models.StringAndArrayCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest7, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest7 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.StringAndArrayCases :return: None @@ -1631,11 +1653,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest8, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest8 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1660,12 +1682,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.MixedLiteralsCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest8, IO[bytes]] = _Unset, + *, + prop: _models.MixedLiteralsCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest8, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest8 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.MixedLiteralsCases :return: None @@ -1815,11 +1841,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest9, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest9 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1844,12 +1870,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", @distributed_trace_async async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.MixedTypesCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest9, IO[bytes]] = _Unset, + *, + prop: _models.MixedTypesCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest9, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest9 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.MixedTypesCases :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/aio/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/models/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/models/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/operations/_operations.py index c40278325a78..35ecb4df66ec 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import UnionClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer @@ -411,11 +411,11 @@ def send(self, *, prop: Literal["a", "b", "c"], content_type: str = "application """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -440,12 +440,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Literal["a", "b", "c"] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest, IO[bytes]] = _Unset, + *, + prop: Literal["a", "b", "c"] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest or IO[bytes] :keyword prop: Is one of the following types: Literal["a"], Literal["b"], Literal["c"] Required. :paramtype prop: str or str or str @@ -596,11 +600,11 @@ def send( """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest1, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest1 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -626,15 +630,15 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements self, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SendRequest1, IO[bytes]] = _Unset, *, prop: Union[Literal["b"], Literal["c"], str] = _Unset, **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest1, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest1 or IO[bytes] :keyword prop: Is one of the following types: Literal["b"], Literal["c"], str Required. :paramtype prop: str or str or str :return: None @@ -788,11 +792,11 @@ def send( """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest2, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -818,15 +822,15 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements self, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SendRequest2, IO[bytes]] = _Unset, *, prop: Union[str, _models.StringExtensibleNamedUnion] = _Unset, **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest2, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest2 or IO[bytes] :keyword prop: Known values are: "b" and "c". Required. :paramtype prop: str or ~typetest.union.models.StringExtensibleNamedUnion :return: None @@ -974,11 +978,11 @@ def send(self, *, prop: Literal[1, 2, 3], content_type: str = "application/json" """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest3, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1003,12 +1007,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Literal[1, 2, 3] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest3, IO[bytes]] = _Unset, + *, + prop: Literal[1, 2, 3] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest3, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest3 or IO[bytes] :keyword prop: Is one of the following types: Literal[1], Literal[2], Literal[3] Required. :paramtype prop: int or int or int :return: None @@ -1156,11 +1164,11 @@ def send(self, *, prop: float, content_type: str = "application/json", **kwargs: """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest4, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest4 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1185,12 +1193,12 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: float = _Unset, **kwargs: Any + self, body: Union[JSON, _types.SendRequest4, IO[bytes]] = _Unset, *, prop: float = _Unset, **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest4, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest4 or IO[bytes] :keyword prop: Is one of the following types: float Required. :paramtype prop: float or float or float :return: None @@ -1340,11 +1348,11 @@ def send( """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest5, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest5 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1369,12 +1377,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Union[_models.Cat, _models.Dog] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest5, IO[bytes]] = _Unset, + *, + prop: Union[_models.Cat, _models.Dog] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest5, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest5 or IO[bytes] :keyword prop: Is either a Cat type or a Dog type. Required. :paramtype prop: ~typetest.union.models.Cat or ~typetest.union.models.Dog :return: None @@ -1522,11 +1534,11 @@ def send(self, *, prop: _models.EnumsOnlyCases, content_type: str = "application """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest6, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest6 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1551,12 +1563,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.EnumsOnlyCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest6, IO[bytes]] = _Unset, + *, + prop: _models.EnumsOnlyCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest6, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest6 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.EnumsOnlyCases :return: None @@ -1704,11 +1720,11 @@ def send(self, *, prop: _models.StringAndArrayCases, content_type: str = "applic """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest7, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest7 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1733,12 +1749,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.StringAndArrayCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest7, IO[bytes]] = _Unset, + *, + prop: _models.StringAndArrayCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest7, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest7 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.StringAndArrayCases :return: None @@ -1886,11 +1906,11 @@ def send(self, *, prop: _models.MixedLiteralsCases, content_type: str = "applica """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest8, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest8 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1915,12 +1935,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.MixedLiteralsCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest8, IO[bytes]] = _Unset, + *, + prop: _models.MixedLiteralsCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest8, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest8 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.MixedLiteralsCases :return: None @@ -2068,11 +2092,11 @@ def send(self, *, prop: _models.MixedTypesCases, content_type: str = "applicatio """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest9, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest9 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2097,12 +2121,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa @distributed_trace def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.MixedTypesCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest9, IO[bytes]] = _Unset, + *, + prop: _models.MixedTypesCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest9, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest9 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.MixedTypesCases :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/operations/_patch.py index ea765788358a..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/operations/_patch.py @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/types.py index 335021e075e3..4494c058991f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/typetest-union/typetest/union/types.py @@ -41,10 +41,10 @@ class EnumsOnlyCases(TypedDict, total=False): :ivar lr: This should be receive/send the left variant. Required. Is one of the following types: Literal["left"], Literal["right"], Literal["up"], Literal["down"] - :vartype lr: str or str or str or str + :vartype lr: Literal["left", "right", "up", "down"] :ivar ud: This should be receive/send the up variant. Required. Is either a Literal["up"] type or a Literal["down"] type. - :vartype ud: str or str + :vartype ud: Literal["up", "down"] """ lr: Required[Literal["left", "right", "up", "down"]] @@ -55,194 +55,194 @@ class EnumsOnlyCases(TypedDict, total=False): Literal[\"down\"] type.""" -class GetResponse(TypedDict, total=False): - """GetResponse. +class MixedLiteralsCases(TypedDict, total=False): + """MixedLiteralsCases. + + :ivar string_literal: This should be receive/send the "a" variant. Required. Is one of the + following types: Literal["a"], Literal[2], float, Literal[True] + :vartype string_literal: Literal["a", 2, True] + :ivar int_literal: This should be receive/send the 2 variant. Required. Is one of the following + types: Literal["a"], Literal[2], float, Literal[True] + :vartype int_literal: Literal["a", 2, True] + :ivar float_literal: This should be receive/send the 3.3 variant. Required. Is one of the + following types: Literal["a"], Literal[2], float, Literal[True] + :vartype float_literal: Literal["a", 2, True] + :ivar boolean_literal: This should be receive/send the true variant. Required. Is one of the + following types: Literal["a"], Literal[2], float, Literal[True] + :vartype boolean_literal: Literal["a", 2, True] + """ + + stringLiteral: Required[Literal["a", 2, True]] + """This should be receive/send the \"a\" variant. Required. Is one of the following types: + Literal[\"a\"], Literal[2], float, Literal[True]""" + intLiteral: Required[Literal["a", 2, True]] + """This should be receive/send the 2 variant. Required. Is one of the following types: + Literal[\"a\"], Literal[2], float, Literal[True]""" + floatLiteral: Required[Literal["a", 2, True]] + """This should be receive/send the 3.3 variant. Required. Is one of the following types: + Literal[\"a\"], Literal[2], float, Literal[True]""" + booleanLiteral: Required[Literal["a", 2, True]] + """This should be receive/send the true variant. Required. Is one of the following types: + Literal[\"a\"], Literal[2], float, Literal[True]""" + + +class MixedTypesCases(TypedDict, total=False): + """MixedTypesCases. + + :ivar model: This should be receive/send the Cat variant. Required. Is one of the following + types: Cat, Literal["a"], int, bool + :vartype model: Union["Cat", Literal["a"], int, bool] + :ivar literal: This should be receive/send the "a" variant. Required. Is one of the following + types: Cat, Literal["a"], int, bool + :vartype literal: Union["Cat", Literal["a"], int, bool] + :ivar int_property: This should be receive/send the int variant. Required. Is one of the + following types: Cat, Literal["a"], int, bool + :vartype int_property: Union["Cat", Literal["a"], int, bool] + :ivar boolean: This should be receive/send the boolean variant. Required. Is one of the + following types: Cat, Literal["a"], int, bool + :vartype boolean: Union["Cat", Literal["a"], int, bool] + :ivar array: This should be receive/send 4 element with Cat, "a", int, and boolean. Required. + :vartype array: list[Union["Cat", Literal["a"], int, bool]] + """ + + model: Required[Union["Cat", Literal["a"], builtins.int, bool]] + """This should be receive/send the Cat variant. Required. Is one of the following types: Cat, + Literal[\"a\"], int, bool""" + literal: Required[Union["Cat", Literal["a"], builtins.int, bool]] + """This should be receive/send the \"a\" variant. Required. Is one of the following types: Cat, + Literal[\"a\"], int, bool""" + int: Required[Union["Cat", Literal["a"], builtins.int, bool]] + """This should be receive/send the int variant. Required. Is one of the following types: Cat, + Literal[\"a\"], int, bool""" + boolean: Required[Union["Cat", Literal["a"], builtins.int, bool]] + """This should be receive/send the boolean variant. Required. Is one of the following types: Cat, + Literal[\"a\"], int, bool""" + array: Required[list[Union["Cat", Literal["a"], builtins.int, bool]]] + """This should be receive/send 4 element with Cat, \"a\", int, and boolean. Required.""" + + +class StringAndArrayCases(TypedDict, total=False): + """StringAndArrayCases. + + :ivar string: This should be receive/send the string variant. Required. Is either a str type or + a [str] type. + :vartype string: Union[str, list[str]] + :ivar array: This should be receive/send the array variant. Required. Is either a str type or a + [str] type. + :vartype array: Union[str, list[str]] + """ + + string: Required[Union[str, list[str]]] + """This should be receive/send the string variant. Required. Is either a str type or a [str] type.""" + array: Required[Union[str, list[str]]] + """This should be receive/send the array variant. Required. Is either a str type or a [str] type.""" + + +class SendRequest(TypedDict, total=False): + """SendRequest. :ivar prop: Required. Is one of the following types: Literal["a"], Literal["b"], Literal["c"] - :vartype prop: str or str or str + :vartype prop: Literal["a", "b", "c"] """ prop: Required[Literal["a", "b", "c"]] """Required. Is one of the following types: Literal[\"a\"], Literal[\"b\"], Literal[\"c\"]""" -class GetResponse1(TypedDict, total=False): - """GetResponse1. +class SendRequest1(TypedDict, total=False): + """SendRequest1. :ivar prop: Required. Is one of the following types: Literal["b"], Literal["c"], str - :vartype prop: str or str or str + :vartype prop: Union[Literal["b"], Literal["c"], str] """ prop: Required[Union[Literal["b"], Literal["c"], str]] """Required. Is one of the following types: Literal[\"b\"], Literal[\"c\"], str""" -class GetResponse2(TypedDict, total=False): - """GetResponse2. +class SendRequest2(TypedDict, total=False): + """SendRequest2. :ivar prop: Required. Known values are: "b" and "c". - :vartype prop: str or ~typetest.union.models.StringExtensibleNamedUnion + :vartype prop: Union[str, "StringExtensibleNamedUnion"] """ prop: Required[Union[str, "StringExtensibleNamedUnion"]] """Required. Known values are: \"b\" and \"c\".""" -class GetResponse3(TypedDict, total=False): - """GetResponse3. +class SendRequest3(TypedDict, total=False): + """SendRequest3. :ivar prop: Required. Is one of the following types: Literal[1], Literal[2], Literal[3] - :vartype prop: int or int or int + :vartype prop: Literal[1, 2, 3] """ prop: Required[Literal[1, 2, 3]] """Required. Is one of the following types: Literal[1], Literal[2], Literal[3]""" -class GetResponse4(TypedDict, total=False): - """GetResponse4. +class SendRequest4(TypedDict, total=False): + """SendRequest4. :ivar prop: Required. Is one of the following types: float - :vartype prop: float or float or float + :vartype prop: float """ prop: Required[float] """Required. Is one of the following types: float""" -class GetResponse5(TypedDict, total=False): - """GetResponse5. +class SendRequest5(TypedDict, total=False): + """SendRequest5. :ivar prop: Required. Is either a Cat type or a Dog type. - :vartype prop: ~typetest.union.models.Cat or ~typetest.union.models.Dog + :vartype prop: Union["Cat", "Dog"] """ prop: Required[Union["Cat", "Dog"]] """Required. Is either a Cat type or a Dog type.""" -class GetResponse6(TypedDict, total=False): - """GetResponse6. +class SendRequest6(TypedDict, total=False): + """SendRequest6. :ivar prop: Required. - :vartype prop: ~typetest.union.models.EnumsOnlyCases + :vartype prop: "EnumsOnlyCases" """ prop: Required["EnumsOnlyCases"] """Required.""" -class GetResponse7(TypedDict, total=False): - """GetResponse7. +class SendRequest7(TypedDict, total=False): + """SendRequest7. :ivar prop: Required. - :vartype prop: ~typetest.union.models.StringAndArrayCases + :vartype prop: "StringAndArrayCases" """ prop: Required["StringAndArrayCases"] """Required.""" -class GetResponse8(TypedDict, total=False): - """GetResponse8. +class SendRequest8(TypedDict, total=False): + """SendRequest8. :ivar prop: Required. - :vartype prop: ~typetest.union.models.MixedLiteralsCases + :vartype prop: "MixedLiteralsCases" """ prop: Required["MixedLiteralsCases"] """Required.""" -class GetResponse9(TypedDict, total=False): - """GetResponse9. +class SendRequest9(TypedDict, total=False): + """SendRequest9. :ivar prop: Required. - :vartype prop: ~typetest.union.models.MixedTypesCases + :vartype prop: "MixedTypesCases" """ prop: Required["MixedTypesCases"] """Required.""" - - -class MixedLiteralsCases(TypedDict, total=False): - """MixedLiteralsCases. - - :ivar string_literal: This should be receive/send the "a" variant. Required. Is one of the - following types: Literal["a"], Literal[2], float, Literal[True] - :vartype string_literal: str or int or float or bool - :ivar int_literal: This should be receive/send the 2 variant. Required. Is one of the following - types: Literal["a"], Literal[2], float, Literal[True] - :vartype int_literal: str or int or float or bool - :ivar float_literal: This should be receive/send the 3.3 variant. Required. Is one of the - following types: Literal["a"], Literal[2], float, Literal[True] - :vartype float_literal: str or int or float or bool - :ivar boolean_literal: This should be receive/send the true variant. Required. Is one of the - following types: Literal["a"], Literal[2], float, Literal[True] - :vartype boolean_literal: str or int or float or bool - """ - - stringLiteral: Required[Literal["a", 2, True]] - """This should be receive/send the \"a\" variant. Required. Is one of the following types: - Literal[\"a\"], Literal[2], float, Literal[True]""" - intLiteral: Required[Literal["a", 2, True]] - """This should be receive/send the 2 variant. Required. Is one of the following types: - Literal[\"a\"], Literal[2], float, Literal[True]""" - floatLiteral: Required[Literal["a", 2, True]] - """This should be receive/send the 3.3 variant. Required. Is one of the following types: - Literal[\"a\"], Literal[2], float, Literal[True]""" - booleanLiteral: Required[Literal["a", 2, True]] - """This should be receive/send the true variant. Required. Is one of the following types: - Literal[\"a\"], Literal[2], float, Literal[True]""" - - -class MixedTypesCases(TypedDict, total=False): - """MixedTypesCases. - - :ivar model: This should be receive/send the Cat variant. Required. Is one of the following - types: Cat, Literal["a"], int, bool - :vartype model: ~typetest.union.models.Cat or str or int or bool - :ivar literal: This should be receive/send the "a" variant. Required. Is one of the following - types: Cat, Literal["a"], int, bool - :vartype literal: ~typetest.union.models.Cat or str or int or bool - :ivar int_property: This should be receive/send the int variant. Required. Is one of the - following types: Cat, Literal["a"], int, bool - :vartype int_property: ~typetest.union.models.Cat or str or int or bool - :ivar boolean: This should be receive/send the boolean variant. Required. Is one of the - following types: Cat, Literal["a"], int, bool - :vartype boolean: ~typetest.union.models.Cat or str or int or bool - :ivar array: This should be receive/send 4 element with Cat, "a", int, and boolean. Required. - :vartype array: list[~typetest.union.models.Cat or str or int or bool] - """ - - model: Required[Union["Cat", Literal["a"], builtins.int, bool]] - """This should be receive/send the Cat variant. Required. Is one of the following types: Cat, - Literal[\"a\"], int, bool""" - literal: Required[Union["Cat", Literal["a"], builtins.int, bool]] - """This should be receive/send the \"a\" variant. Required. Is one of the following types: Cat, - Literal[\"a\"], int, bool""" - int: Required[Union["Cat", Literal["a"], builtins.int, bool]] - """This should be receive/send the int variant. Required. Is one of the following types: Cat, - Literal[\"a\"], int, bool""" - boolean: Required[Union["Cat", Literal["a"], builtins.int, bool]] - """This should be receive/send the boolean variant. Required. Is one of the following types: Cat, - Literal[\"a\"], int, bool""" - array: Required[list[Union["Cat", Literal["a"], builtins.int, bool]]] - """This should be receive/send 4 element with Cat, \"a\", int, and boolean. Required.""" - - -class StringAndArrayCases(TypedDict, total=False): - """StringAndArrayCases. - - :ivar string: This should be receive/send the string variant. Required. Is either a str type or - a [str] type. - :vartype string: str or list[str] - :ivar array: This should be receive/send the array variant. Required. Is either a str type or a - [str] type. - :vartype array: str or list[str] - """ - - string: Required[Union[str, list[str]]] - """This should be receive/send the string variant. Required. Is either a str type or a [str] type.""" - array: Required[Union[str, list[str]]] - """This should be receive/send the array variant. Required. Is either a str type or a [str] type.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/pyproject.toml index 23d3bce7e24e..2dda6344979a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/operations/_operations.py index 9cb3c13a4b56..490a29de43c8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ..._utils.utils import ClientMixinABC @@ -39,7 +39,6 @@ ) from .._configuration import AddedClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -79,12 +78,12 @@ async def v2_in_interface( @overload async def v2_in_interface( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV2: """v2_in_interface. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -115,11 +114,13 @@ async def v2_in_interface( params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - async def v2_in_interface(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + async def v2_in_interface( + self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV2 or ~versioning.added.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.added.models.ModelV2 :raises ~azure.core.exceptions.HttpResponseError: @@ -209,12 +210,12 @@ async def v1( @overload async def v1( - self, body: JSON, *, header_v2: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV1, *, header_v2: str, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV1: """v1. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV1 :keyword header_v2: Required. :paramtype header_v2: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -249,12 +250,12 @@ async def v1( api_versions_list=["v1", "v2"], ) async def v1( - self, body: Union[_models.ModelV1, JSON, IO[bytes]], *, header_v2: str, **kwargs: Any + self, body: Union[_models.ModelV1, _types.ModelV1, IO[bytes]], *, header_v2: str, **kwargs: Any ) -> _models.ModelV1: """v1. - :param body: Is one of the following types: ModelV1, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV1 or JSON or IO[bytes] + :param body: Is either a ModelV1 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV1 or ~versioning.added.types.ModelV1 or IO[bytes] :keyword header_v2: Required. :paramtype header_v2: str :return: ModelV1. The ModelV1 is compatible with MutableMapping @@ -339,11 +340,13 @@ async def v2( """ @overload - async def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + async def v2( + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -372,11 +375,11 @@ async def v2(self, body: IO[bytes], *, content_type: str = "application/json", * params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - async def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + async def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV2 or ~versioning.added.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.added.models.ModelV2 :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/models/_models.py index 00c1ffc3add4..5b4d7ef0632a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/models/_models.py @@ -12,7 +12,7 @@ from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - from .. import _types, models as _models + from .. import _unions, models as _models class ModelV1(_Model): @@ -32,7 +32,7 @@ class ModelV1(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Known values are: \"enumMemberV1\" and \"enumMemberV2\".""" - union_prop: "_types.UnionV1" = rest_field( + union_prop: "_unions.UnionV1" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a int type.""" @@ -43,7 +43,7 @@ def __init__( *, prop: str, enum_prop: Union[str, "_models.EnumV1"], - union_prop: "_types.UnionV1", + union_prop: "_unions.UnionV1", ) -> None: ... @overload @@ -74,7 +74,7 @@ class ModelV2(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. \"enumMember\"""" - union_prop: "_types.UnionV2" = rest_field( + union_prop: "_unions.UnionV2" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a int type.""" @@ -85,7 +85,7 @@ def __init__( *, prop: str, enum_prop: Union[str, "_models.EnumV2"], - union_prop: "_types.UnionV2", + union_prop: "_unions.UnionV2", ) -> None: ... @overload diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/operations/_operations.py index e9cbeb879bd0..d28a00fbe23c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/operations/_operations.py @@ -26,14 +26,13 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import AddedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer from .._utils.utils import ClientMixinABC from .._validation import api_version_validation -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -127,11 +126,13 @@ def v2_in_interface( """ @overload - def v2_in_interface(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + def v2_in_interface( + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -162,11 +163,13 @@ def v2_in_interface( params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - def v2_in_interface(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + def v2_in_interface( + self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV2 or ~versioning.added.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.added.models.ModelV2 :raises ~azure.core.exceptions.HttpResponseError: @@ -254,12 +257,12 @@ def v1( @overload def v1( - self, body: JSON, *, header_v2: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV1, *, header_v2: str, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV1: """v1. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV1 :keyword header_v2: Required. :paramtype header_v2: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -293,11 +296,13 @@ def v1( params_added_on={"v2": ["header_v2"]}, api_versions_list=["v1", "v2"], ) - def v1(self, body: Union[_models.ModelV1, JSON, IO[bytes]], *, header_v2: str, **kwargs: Any) -> _models.ModelV1: + def v1( + self, body: Union[_models.ModelV1, _types.ModelV1, IO[bytes]], *, header_v2: str, **kwargs: Any + ) -> _models.ModelV1: """v1. - :param body: Is one of the following types: ModelV1, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV1 or JSON or IO[bytes] + :param body: Is either a ModelV1 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV1 or ~versioning.added.types.ModelV1 or IO[bytes] :keyword header_v2: Required. :paramtype header_v2: str :return: ModelV1. The ModelV1 is compatible with MutableMapping @@ -380,11 +385,11 @@ def v2(self, body: _models.ModelV2, *, content_type: str = "application/json", * """ @overload - def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + def v2(self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -413,11 +418,11 @@ def v2(self, body: IO[bytes], *, content_type: str = "application/json", **kwarg params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV2 or ~versioning.added.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.added.models.ModelV2 :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/types.py index 5ef150467a86..4d12103c76c8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-added/versioning/added/types.py @@ -20,9 +20,9 @@ class ModelV1(TypedDict, total=False): :ivar prop: Required. :vartype prop: str :ivar enum_prop: Required. Known values are: "enumMemberV1" and "enumMemberV2". - :vartype enum_prop: str or ~versioning.added.models.EnumV1 + :vartype enum_prop: Union[str, "EnumV1"] :ivar union_prop: Required. Is either a str type or a int type. - :vartype union_prop: str or int + :vartype union_prop: "_unions.UnionV1" """ prop: Required[str] @@ -39,9 +39,9 @@ class ModelV2(TypedDict, total=False): :ivar prop: Required. :vartype prop: str :ivar enum_prop: Required. "enumMember" - :vartype enum_prop: str or ~versioning.added.models.EnumV2 + :vartype enum_prop: Union[str, "EnumV2"] :ivar union_prop: Required. Is either a str type or a int type. - :vartype union_prop: str or int + :vartype union_prop: "_unions.UnionV2" """ prop: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/pyproject.toml index 9a4cac941df3..d7af8fb20e62 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_operations/_operations.py index 54870b75c021..b46bf5273303 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import MadeOptionalClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -91,12 +90,17 @@ def test( @overload def test( - self, body: JSON, *, param: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + self, + body: _types.TestModel, + *, + param: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any ) -> _models.TestModel: """test. :param body: Required. - :type body: JSON + :type body: ~versioning.madeoptional.types.TestModel :keyword param: Default value is None. :paramtype param: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -127,12 +131,13 @@ def test( @distributed_trace def test( - self, body: Union[_models.TestModel, JSON, IO[bytes]], *, param: Optional[str] = None, **kwargs: Any + self, body: Union[_models.TestModel, _types.TestModel, IO[bytes]], *, param: Optional[str] = None, **kwargs: Any ) -> _models.TestModel: """test. - :param body: Is one of the following types: TestModel, JSON, IO[bytes] Required. - :type body: ~versioning.madeoptional.models.TestModel or JSON or IO[bytes] + :param body: Is either a TestModel type or a IO[bytes] type. Required. + :type body: ~versioning.madeoptional.models.TestModel or + ~versioning.madeoptional.types.TestModel or IO[bytes] :keyword param: Default value is None. :paramtype param: str :return: TestModel. The TestModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_operations/_operations.py index 6f264d9e9a3e..79475047b0ee 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_operations/_operations.py @@ -27,13 +27,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_made_optional_test_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import MadeOptionalClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -67,12 +66,17 @@ async def test( @overload async def test( - self, body: JSON, *, param: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + self, + body: _types.TestModel, + *, + param: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any ) -> _models.TestModel: """test. :param body: Required. - :type body: JSON + :type body: ~versioning.madeoptional.types.TestModel :keyword param: Default value is None. :paramtype param: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -103,12 +107,13 @@ async def test( @distributed_trace_async async def test( - self, body: Union[_models.TestModel, JSON, IO[bytes]], *, param: Optional[str] = None, **kwargs: Any + self, body: Union[_models.TestModel, _types.TestModel, IO[bytes]], *, param: Optional[str] = None, **kwargs: Any ) -> _models.TestModel: """test. - :param body: Is one of the following types: TestModel, JSON, IO[bytes] Required. - :type body: ~versioning.madeoptional.models.TestModel or JSON or IO[bytes] + :param body: Is either a TestModel type or a IO[bytes] type. Required. + :type body: ~versioning.madeoptional.models.TestModel or + ~versioning.madeoptional.types.TestModel or IO[bytes] :keyword param: Default value is None. :paramtype param: str :return: TestModel. The TestModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-madeoptional/versioning/madeoptional/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/pyproject.toml index 45fe86465d6c..b887365a0f26 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_operations/_operations.py index 037f4cac1e0e..b87a9e84ecbb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import RemovedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -93,11 +92,11 @@ def v2(self, body: _models.ModelV2, *, content_type: str = "application/json", * """ @overload - def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + def v2(self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~versioning.removed.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -121,11 +120,12 @@ def v2(self, body: IO[bytes], *, content_type: str = "application/json", **kwarg """ @distributed_trace - def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.removed.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.removed.models.ModelV2 or ~versioning.removed.types.ModelV2 or + IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.removed.models.ModelV2 :raises ~azure.core.exceptions.HttpResponseError: @@ -208,12 +208,14 @@ def model_v3( """ @overload - def model_v3(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV3: + def model_v3( + self, body: _types.ModelV3, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV3: """This operation will pass different paths and different request bodies based on different versions. :param body: Required. - :type body: JSON + :type body: ~versioning.removed.types.ModelV3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -238,12 +240,13 @@ def model_v3(self, body: IO[bytes], *, content_type: str = "application/json", * """ @distributed_trace - def model_v3(self, body: Union[_models.ModelV3, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV3: + def model_v3(self, body: Union[_models.ModelV3, _types.ModelV3, IO[bytes]], **kwargs: Any) -> _models.ModelV3: """This operation will pass different paths and different request bodies based on different versions. - :param body: Is one of the following types: ModelV3, JSON, IO[bytes] Required. - :type body: ~versioning.removed.models.ModelV3 or JSON or IO[bytes] + :param body: Is either a ModelV3 type or a IO[bytes] type. Required. + :type body: ~versioning.removed.models.ModelV3 or ~versioning.removed.types.ModelV3 or + IO[bytes] :return: ModelV3. The ModelV3 is compatible with MutableMapping :rtype: ~versioning.removed.models.ModelV3 :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_operations/_operations.py index f873847aa390..12d9645db3e4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_operations/_operations.py @@ -27,13 +27,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_removed_model_v3_request, build_removed_v2_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import RemovedClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -59,11 +58,13 @@ async def v2( """ @overload - async def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + async def v2( + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~versioning.removed.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -87,11 +88,12 @@ async def v2(self, body: IO[bytes], *, content_type: str = "application/json", * """ @distributed_trace_async - async def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + async def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.removed.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.removed.models.ModelV2 or ~versioning.removed.types.ModelV2 or + IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.removed.models.ModelV2 :raises ~azure.core.exceptions.HttpResponseError: @@ -174,12 +176,14 @@ async def model_v3( """ @overload - async def model_v3(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV3: + async def model_v3( + self, body: _types.ModelV3, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV3: """This operation will pass different paths and different request bodies based on different versions. :param body: Required. - :type body: JSON + :type body: ~versioning.removed.types.ModelV3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -206,12 +210,13 @@ async def model_v3( """ @distributed_trace_async - async def model_v3(self, body: Union[_models.ModelV3, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV3: + async def model_v3(self, body: Union[_models.ModelV3, _types.ModelV3, IO[bytes]], **kwargs: Any) -> _models.ModelV3: """This operation will pass different paths and different request bodies based on different versions. - :param body: Is one of the following types: ModelV3, JSON, IO[bytes] Required. - :type body: ~versioning.removed.models.ModelV3 or JSON or IO[bytes] + :param body: Is either a ModelV3 type or a IO[bytes] type. Required. + :type body: ~versioning.removed.models.ModelV3 or ~versioning.removed.types.ModelV3 or + IO[bytes] :return: ModelV3. The ModelV3 is compatible with MutableMapping :rtype: ~versioning.removed.models.ModelV3 :raises ~azure.core.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/models/_models.py index 6b0caf6b2b5b..81b0feab35a4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/models/_models.py @@ -12,7 +12,7 @@ from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - from .. import _types, models as _models + from .. import _unions, models as _models class ModelV2(_Model): @@ -32,7 +32,7 @@ class ModelV2(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. \"enumMemberV2\"""" - union_prop: "_types.UnionV2" = rest_field( + union_prop: "_unions.UnionV2" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a float type.""" @@ -43,7 +43,7 @@ def __init__( *, prop: str, enum_prop: Union[str, "_models.EnumV2"], - union_prop: "_types.UnionV2", + union_prop: "_unions.UnionV2", ) -> None: ... @overload diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/types.py index ff89d3714691..d351ce4c13e2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-removed/versioning/removed/types.py @@ -20,9 +20,9 @@ class ModelV2(TypedDict, total=False): :ivar prop: Required. :vartype prop: str :ivar enum_prop: Required. "enumMemberV2" - :vartype enum_prop: str or ~versioning.removed.models.EnumV2 + :vartype enum_prop: Union[str, "EnumV2"] :ivar union_prop: Required. Is either a str type or a float type. - :vartype union_prop: str or float + :vartype union_prop: "_unions.UnionV2" """ prop: Required[str] @@ -39,7 +39,7 @@ class ModelV3(TypedDict, total=False): :ivar id: Required. :vartype id: str :ivar enum_prop: Required. Known values are: "enumMemberV1" and "enumMemberV2Preview". - :vartype enum_prop: str or ~versioning.removed.models.EnumV3 + :vartype enum_prop: Union[str, "EnumV3"] """ id: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/pyproject.toml index 750a3143a3c8..c56d20d73850 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_operations.py index 02a26027ff1e..c8ea34a03881 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_operations.py @@ -27,7 +27,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ..._utils.utils import ClientMixinABC @@ -37,7 +37,6 @@ ) from .._configuration import RenamedFromClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -77,12 +76,12 @@ async def new_op_in_new_interface( @overload async def new_op_in_new_interface( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.NewModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.NewModel: """new_op_in_new_interface. :param body: Required. - :type body: JSON + :type body: ~versioning.renamedfrom.types.NewModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -109,12 +108,13 @@ async def new_op_in_new_interface( @distributed_trace_async async def new_op_in_new_interface( - self, body: Union[_models.NewModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.NewModel, _types.NewModel, IO[bytes]], **kwargs: Any ) -> _models.NewModel: """new_op_in_new_interface. - :param body: Is one of the following types: NewModel, JSON, IO[bytes] Required. - :type body: ~versioning.renamedfrom.models.NewModel or JSON or IO[bytes] + :param body: Is either a NewModel type or a IO[bytes] type. Required. + :type body: ~versioning.renamedfrom.models.NewModel or ~versioning.renamedfrom.types.NewModel + or IO[bytes] :return: NewModel. The NewModel is compatible with MutableMapping :rtype: ~versioning.renamedfrom.models.NewModel :raises ~azure.core.exceptions.HttpResponseError: @@ -204,12 +204,12 @@ async def new_op( @overload async def new_op( - self, body: JSON, *, new_query: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.NewModel, *, new_query: str, content_type: str = "application/json", **kwargs: Any ) -> _models.NewModel: """new_op. :param body: Required. - :type body: JSON + :type body: ~versioning.renamedfrom.types.NewModel :keyword new_query: Required. :paramtype new_query: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -240,12 +240,13 @@ async def new_op( @distributed_trace_async async def new_op( - self, body: Union[_models.NewModel, JSON, IO[bytes]], *, new_query: str, **kwargs: Any + self, body: Union[_models.NewModel, _types.NewModel, IO[bytes]], *, new_query: str, **kwargs: Any ) -> _models.NewModel: """new_op. - :param body: Is one of the following types: NewModel, JSON, IO[bytes] Required. - :type body: ~versioning.renamedfrom.models.NewModel or JSON or IO[bytes] + :param body: Is either a NewModel type or a IO[bytes] type. Required. + :type body: ~versioning.renamedfrom.models.NewModel or ~versioning.renamedfrom.types.NewModel + or IO[bytes] :keyword new_query: Required. :paramtype new_query: str :return: NewModel. The NewModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/models/_models.py index 0683fe19dee2..700e605a90df 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/models/_models.py @@ -12,7 +12,7 @@ from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - from .. import _types, models as _models + from .. import _unions, models as _models class NewModel(_Model): @@ -32,7 +32,7 @@ class NewModel(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. \"newEnumMember\"""" - union_prop: "_types.NewUnion" = rest_field( + union_prop: "_unions.NewUnion" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a int type.""" @@ -43,7 +43,7 @@ def __init__( *, new_prop: str, enum_prop: Union[str, "_models.NewEnum"], - union_prop: "_types.NewUnion", + union_prop: "_unions.NewUnion", ) -> None: ... @overload diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/operations/_operations.py index b98aebb73fe5..e8778ec8a3a4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import RenamedFromClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -113,12 +112,12 @@ def new_op_in_new_interface( @overload def new_op_in_new_interface( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.NewModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.NewModel: """new_op_in_new_interface. :param body: Required. - :type body: JSON + :type body: ~versioning.renamedfrom.types.NewModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -145,12 +144,13 @@ def new_op_in_new_interface( @distributed_trace def new_op_in_new_interface( - self, body: Union[_models.NewModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.NewModel, _types.NewModel, IO[bytes]], **kwargs: Any ) -> _models.NewModel: """new_op_in_new_interface. - :param body: Is one of the following types: NewModel, JSON, IO[bytes] Required. - :type body: ~versioning.renamedfrom.models.NewModel or JSON or IO[bytes] + :param body: Is either a NewModel type or a IO[bytes] type. Required. + :type body: ~versioning.renamedfrom.models.NewModel or ~versioning.renamedfrom.types.NewModel + or IO[bytes] :return: NewModel. The NewModel is compatible with MutableMapping :rtype: ~versioning.renamedfrom.models.NewModel :raises ~azure.core.exceptions.HttpResponseError: @@ -240,12 +240,12 @@ def new_op( @overload def new_op( - self, body: JSON, *, new_query: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.NewModel, *, new_query: str, content_type: str = "application/json", **kwargs: Any ) -> _models.NewModel: """new_op. :param body: Required. - :type body: JSON + :type body: ~versioning.renamedfrom.types.NewModel :keyword new_query: Required. :paramtype new_query: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -276,12 +276,13 @@ def new_op( @distributed_trace def new_op( - self, body: Union[_models.NewModel, JSON, IO[bytes]], *, new_query: str, **kwargs: Any + self, body: Union[_models.NewModel, _types.NewModel, IO[bytes]], *, new_query: str, **kwargs: Any ) -> _models.NewModel: """new_op. - :param body: Is one of the following types: NewModel, JSON, IO[bytes] Required. - :type body: ~versioning.renamedfrom.models.NewModel or JSON or IO[bytes] + :param body: Is either a NewModel type or a IO[bytes] type. Required. + :type body: ~versioning.renamedfrom.models.NewModel or ~versioning.renamedfrom.types.NewModel + or IO[bytes] :keyword new_query: Required. :paramtype new_query: str :return: NewModel. The NewModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/types.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/types.py index 22bcd4962fc4..36fe0d898a1d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-renamedfrom/versioning/renamedfrom/types.py @@ -20,9 +20,9 @@ class NewModel(TypedDict, total=False): :ivar new_prop: Required. :vartype new_prop: str :ivar enum_prop: Required. "newEnumMember" - :vartype enum_prop: str or ~versioning.renamedfrom.models.NewEnum + :vartype enum_prop: Union[str, "NewEnum"] :ivar union_prop: Required. Is either a str type or a int type. - :vartype union_prop: str or int + :vartype union_prop: "_unions.NewUnion" """ newProp: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/pyproject.toml index 00744a792e00..63b685c0083a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-returntypechangedfrom/versioning/returntypechangedfrom/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/pyproject.toml index 0be623bdae2f..f68168d22bf8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_operations.py index 993eb877123c..e1e2ee46e425 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_operations.py @@ -26,13 +26,12 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import TypeChangedFromClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -85,12 +84,12 @@ def test( @overload def test( - self, body: JSON, *, param: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.TestModel, *, param: str, content_type: str = "application/json", **kwargs: Any ) -> _models.TestModel: """test. :param body: Required. - :type body: JSON + :type body: ~versioning.typechangedfrom.types.TestModel :keyword param: Required. :paramtype param: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -120,11 +119,14 @@ def test( """ @distributed_trace - def test(self, body: Union[_models.TestModel, JSON, IO[bytes]], *, param: str, **kwargs: Any) -> _models.TestModel: + def test( + self, body: Union[_models.TestModel, _types.TestModel, IO[bytes]], *, param: str, **kwargs: Any + ) -> _models.TestModel: """test. - :param body: Is one of the following types: TestModel, JSON, IO[bytes] Required. - :type body: ~versioning.typechangedfrom.models.TestModel or JSON or IO[bytes] + :param body: Is either a TestModel type or a IO[bytes] type. Required. + :type body: ~versioning.typechangedfrom.models.TestModel or + ~versioning.typechangedfrom.types.TestModel or IO[bytes] :keyword param: Required. :paramtype param: str :return: TestModel. The TestModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_utils/model_base.py index d725c55906d3..0f2c5bdfe70f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_utils/model_base.py @@ -109,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -301,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -330,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -425,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -449,7 +482,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -484,19 +517,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -509,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -564,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_utils/serialization.py index a088671e9c51..75906e2eb77f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/_utils/serialization.py @@ -520,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1109,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1381,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1393,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1954,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_operations.py index 2658f0b11382..20d9a5481aed 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_operations.py @@ -27,13 +27,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_type_changed_from_test_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import TypeChangedFromClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -62,12 +61,12 @@ async def test( @overload async def test( - self, body: JSON, *, param: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.TestModel, *, param: str, content_type: str = "application/json", **kwargs: Any ) -> _models.TestModel: """test. :param body: Required. - :type body: JSON + :type body: ~versioning.typechangedfrom.types.TestModel :keyword param: Required. :paramtype param: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -98,12 +97,13 @@ async def test( @distributed_trace_async async def test( - self, body: Union[_models.TestModel, JSON, IO[bytes]], *, param: str, **kwargs: Any + self, body: Union[_models.TestModel, _types.TestModel, IO[bytes]], *, param: str, **kwargs: Any ) -> _models.TestModel: """test. - :param body: Is one of the following types: TestModel, JSON, IO[bytes] Required. - :type body: ~versioning.typechangedfrom.models.TestModel or JSON or IO[bytes] + :param body: Is either a TestModel type or a IO[bytes] type. Required. + :type body: ~versioning.typechangedfrom.models.TestModel or + ~versioning.typechangedfrom.types.TestModel or IO[bytes] :keyword param: Required. :paramtype param: str :return: TestModel. The TestModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/aio/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/models/_patch.py index b6400f50d7ce..87676c65a8f0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/azure/versioning-typechangedfrom/versioning/typechangedfrom/models/_patch.py @@ -8,9 +8,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/authentication/apikey/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/authentication/apikey/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/authentication/apikey/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/authentication/apikey/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/authentication/apikey/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/authentication/apikey/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/authentication/apikey/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/authentication/apikey/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/pyproject.toml index a3dff4026945..5a93438ed5a9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-api-key/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/types.py deleted file mode 100644 index 2f708b57c18d..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/authentication/http/custom/types.py +++ /dev/null @@ -1,14 +0,0 @@ -# coding=utf-8 - -from typing_extensions import Required, TypedDict - - -class InvalidAuth(TypedDict, total=False): - """InvalidAuth. - - :ivar error: Required. - :vartype error: str - """ - - error: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/pyproject.toml index 8d9373ed5369..aaca531d7617 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-http-custom/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/aio/_operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/aio/_operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/aio/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/authentication/noauth/union/aio/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/pyproject.toml index eda5789e71bb..931150164b55 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-noauth-union/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/types.py deleted file mode 100644 index 2f708b57c18d..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/authentication/oauth2/types.py +++ /dev/null @@ -1,14 +0,0 @@ -# coding=utf-8 - -from typing_extensions import Required, TypedDict - - -class InvalidAuth(TypedDict, total=False): - """InvalidAuth. - - :ivar error: Required. - :vartype error: str - """ - - error: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/pyproject.toml index f7872e2910e7..bc0c5d47e820 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-oauth2/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/authentication/union/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/pyproject.toml index 27e808c510e9..73f5c9258d91 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/authentication-union/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/property/aio/operations/_operations.py index 1e14bdd2a72d..2edadd55dda6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/property/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/property/aio/operations/_operations.py @@ -20,7 +20,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .... import models as _models3 +from .... import models as _models3, types as _types_models3 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import ArrayClientConfiguration @@ -39,7 +39,6 @@ build_property_space_delimited_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -80,12 +79,12 @@ async def comma_delimited( @overload async def comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.CommaDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.CommaDelimitedArrayProperty: """comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -113,13 +112,15 @@ async def comma_delimited( """ async def comma_delimited( - self, body: Union[_models3.CommaDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.CommaDelimitedArrayProperty, _types_models3.CommaDelimitedArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models3.CommaDelimitedArrayProperty: """comma_delimited. - :param body: Is one of the following types: CommaDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.CommaDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.CommaDelimitedArrayProperty or + ~encode.array.types.CommaDelimitedArrayProperty or IO[bytes] :return: CommaDelimitedArrayProperty. The CommaDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedArrayProperty @@ -201,12 +202,12 @@ async def space_delimited( @overload async def space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.SpaceDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.SpaceDelimitedArrayProperty: """space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -234,13 +235,15 @@ async def space_delimited( """ async def space_delimited( - self, body: Union[_models3.SpaceDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.SpaceDelimitedArrayProperty, _types_models3.SpaceDelimitedArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models3.SpaceDelimitedArrayProperty: """space_delimited. - :param body: Is one of the following types: SpaceDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.SpaceDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.SpaceDelimitedArrayProperty or + ~encode.array.types.SpaceDelimitedArrayProperty or IO[bytes] :return: SpaceDelimitedArrayProperty. The SpaceDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedArrayProperty @@ -322,12 +325,12 @@ async def pipe_delimited( @overload async def pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.PipeDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.PipeDelimitedArrayProperty: """pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -355,13 +358,15 @@ async def pipe_delimited( """ async def pipe_delimited( - self, body: Union[_models3.PipeDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.PipeDelimitedArrayProperty, _types_models3.PipeDelimitedArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models3.PipeDelimitedArrayProperty: """pipe_delimited. - :param body: Is one of the following types: PipeDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.PipeDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.PipeDelimitedArrayProperty or + ~encode.array.types.PipeDelimitedArrayProperty or IO[bytes] :return: PipeDelimitedArrayProperty. The PipeDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedArrayProperty @@ -443,12 +448,16 @@ async def newline_delimited( @overload async def newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.NewlineDelimitedArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.NewlineDelimitedArrayProperty: """newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -476,13 +485,15 @@ async def newline_delimited( """ async def newline_delimited( - self, body: Union[_models3.NewlineDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.NewlineDelimitedArrayProperty, _types_models3.NewlineDelimitedArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models3.NewlineDelimitedArrayProperty: """newline_delimited. - :param body: Is one of the following types: NewlineDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.NewlineDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a NewlineDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.NewlineDelimitedArrayProperty or + ~encode.array.types.NewlineDelimitedArrayProperty or IO[bytes] :return: NewlineDelimitedArrayProperty. The NewlineDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedArrayProperty @@ -564,12 +575,16 @@ async def enum_comma_delimited( @overload async def enum_comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.CommaDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.CommaDelimitedEnumArrayProperty: """enum_comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -597,13 +612,17 @@ async def enum_comma_delimited( """ async def enum_comma_delimited( - self, body: Union[_models3.CommaDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.CommaDelimitedEnumArrayProperty, _types_models3.CommaDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any ) -> _models3.CommaDelimitedEnumArrayProperty: """enum_comma_delimited. - :param body: Is one of the following types: CommaDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.CommaDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.CommaDelimitedEnumArrayProperty or + ~encode.array.types.CommaDelimitedEnumArrayProperty or IO[bytes] :return: CommaDelimitedEnumArrayProperty. The CommaDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedEnumArrayProperty @@ -685,12 +704,16 @@ async def enum_space_delimited( @overload async def enum_space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.SpaceDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.SpaceDelimitedEnumArrayProperty: """enum_space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -718,13 +741,17 @@ async def enum_space_delimited( """ async def enum_space_delimited( - self, body: Union[_models3.SpaceDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.SpaceDelimitedEnumArrayProperty, _types_models3.SpaceDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any ) -> _models3.SpaceDelimitedEnumArrayProperty: """enum_space_delimited. - :param body: Is one of the following types: SpaceDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.SpaceDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.SpaceDelimitedEnumArrayProperty or + ~encode.array.types.SpaceDelimitedEnumArrayProperty or IO[bytes] :return: SpaceDelimitedEnumArrayProperty. The SpaceDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedEnumArrayProperty @@ -806,12 +833,16 @@ async def enum_pipe_delimited( @overload async def enum_pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.PipeDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.PipeDelimitedEnumArrayProperty: """enum_pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -839,13 +870,15 @@ async def enum_pipe_delimited( """ async def enum_pipe_delimited( - self, body: Union[_models3.PipeDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.PipeDelimitedEnumArrayProperty, _types_models3.PipeDelimitedEnumArrayProperty, IO[bytes]], + **kwargs: Any ) -> _models3.PipeDelimitedEnumArrayProperty: """enum_pipe_delimited. - :param body: Is one of the following types: PipeDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.PipeDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.PipeDelimitedEnumArrayProperty or + ~encode.array.types.PipeDelimitedEnumArrayProperty or IO[bytes] :return: PipeDelimitedEnumArrayProperty. The PipeDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedEnumArrayProperty @@ -927,12 +960,16 @@ async def enum_newline_delimited( @overload async def enum_newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.NewlineDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.NewlineDelimitedEnumArrayProperty: """enum_newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -960,13 +997,17 @@ async def enum_newline_delimited( """ async def enum_newline_delimited( - self, body: Union[_models3.NewlineDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.NewlineDelimitedEnumArrayProperty, _types_models3.NewlineDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any ) -> _models3.NewlineDelimitedEnumArrayProperty: """enum_newline_delimited. - :param body: Is one of the following types: NewlineDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.NewlineDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a NewlineDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.NewlineDelimitedEnumArrayProperty or + ~encode.array.types.NewlineDelimitedEnumArrayProperty or IO[bytes] :return: NewlineDelimitedEnumArrayProperty. The NewlineDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedEnumArrayProperty @@ -1052,12 +1093,16 @@ async def extensible_enum_comma_delimited( @overload async def extensible_enum_comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.CommaDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.CommaDelimitedExtensibleEnumArrayProperty: """extensible_enum_comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1085,13 +1130,20 @@ async def extensible_enum_comma_delimited( """ async def extensible_enum_comma_delimited( - self, body: Union[_models3.CommaDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.CommaDelimitedExtensibleEnumArrayProperty, + _types_models3.CommaDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models3.CommaDelimitedExtensibleEnumArrayProperty: """extensible_enum_comma_delimited. - :param body: Is one of the following types: CommaDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.CommaDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: CommaDelimitedExtensibleEnumArrayProperty. The CommaDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty @@ -1177,12 +1229,16 @@ async def extensible_enum_space_delimited( @overload async def extensible_enum_space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.SpaceDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.SpaceDelimitedExtensibleEnumArrayProperty: """extensible_enum_space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1210,13 +1266,20 @@ async def extensible_enum_space_delimited( """ async def extensible_enum_space_delimited( - self, body: Union[_models3.SpaceDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.SpaceDelimitedExtensibleEnumArrayProperty, + _types_models3.SpaceDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models3.SpaceDelimitedExtensibleEnumArrayProperty: """extensible_enum_space_delimited. - :param body: Is one of the following types: SpaceDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.SpaceDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: SpaceDelimitedExtensibleEnumArrayProperty. The SpaceDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty @@ -1302,12 +1365,16 @@ async def extensible_enum_pipe_delimited( @overload async def extensible_enum_pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.PipeDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.PipeDelimitedExtensibleEnumArrayProperty: """extensible_enum_pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1335,13 +1402,20 @@ async def extensible_enum_pipe_delimited( """ async def extensible_enum_pipe_delimited( - self, body: Union[_models3.PipeDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.PipeDelimitedExtensibleEnumArrayProperty, + _types_models3.PipeDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models3.PipeDelimitedExtensibleEnumArrayProperty: """extensible_enum_pipe_delimited. - :param body: Is one of the following types: PipeDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.PipeDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: PipeDelimitedExtensibleEnumArrayProperty. The PipeDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty @@ -1427,12 +1501,16 @@ async def extensible_enum_newline_delimited( @overload async def extensible_enum_newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.NewlineDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.NewlineDelimitedExtensibleEnumArrayProperty: """extensible_enum_newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1460,14 +1538,20 @@ async def extensible_enum_newline_delimited( """ async def extensible_enum_newline_delimited( - self, body: Union[_models3.NewlineDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.NewlineDelimitedExtensibleEnumArrayProperty, + _types_models3.NewlineDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models3.NewlineDelimitedExtensibleEnumArrayProperty: """extensible_enum_newline_delimited. - :param body: Is one of the following types: NewlineDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty or JSON or - IO[bytes] + :param body: Is either a NewlineDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.NewlineDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: NewlineDelimitedExtensibleEnumArrayProperty. The NewlineDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/property/operations/_operations.py index 0abf4fcc9d77..8b121b69d91e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/property/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/property/operations/_operations.py @@ -20,12 +20,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..._configuration import ArrayClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -281,12 +280,12 @@ def comma_delimited( @overload def comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.CommaDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.CommaDelimitedArrayProperty: """comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -314,13 +313,15 @@ def comma_delimited( """ def comma_delimited( - self, body: Union[_models2.CommaDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.CommaDelimitedArrayProperty, _types_models2.CommaDelimitedArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models2.CommaDelimitedArrayProperty: """comma_delimited. - :param body: Is one of the following types: CommaDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.CommaDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.CommaDelimitedArrayProperty or + ~encode.array.types.CommaDelimitedArrayProperty or IO[bytes] :return: CommaDelimitedArrayProperty. The CommaDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedArrayProperty @@ -402,12 +403,12 @@ def space_delimited( @overload def space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.SpaceDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.SpaceDelimitedArrayProperty: """space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -435,13 +436,15 @@ def space_delimited( """ def space_delimited( - self, body: Union[_models2.SpaceDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.SpaceDelimitedArrayProperty, _types_models2.SpaceDelimitedArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models2.SpaceDelimitedArrayProperty: """space_delimited. - :param body: Is one of the following types: SpaceDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.SpaceDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.SpaceDelimitedArrayProperty or + ~encode.array.types.SpaceDelimitedArrayProperty or IO[bytes] :return: SpaceDelimitedArrayProperty. The SpaceDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedArrayProperty @@ -523,12 +526,12 @@ def pipe_delimited( @overload def pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.PipeDelimitedArrayProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.PipeDelimitedArrayProperty: """pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -556,13 +559,15 @@ def pipe_delimited( """ def pipe_delimited( - self, body: Union[_models2.PipeDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.PipeDelimitedArrayProperty, _types_models2.PipeDelimitedArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models2.PipeDelimitedArrayProperty: """pipe_delimited. - :param body: Is one of the following types: PipeDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.PipeDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.PipeDelimitedArrayProperty or + ~encode.array.types.PipeDelimitedArrayProperty or IO[bytes] :return: PipeDelimitedArrayProperty. The PipeDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedArrayProperty @@ -644,12 +649,16 @@ def newline_delimited( @overload def newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.NewlineDelimitedArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.NewlineDelimitedArrayProperty: """newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -677,13 +686,15 @@ def newline_delimited( """ def newline_delimited( - self, body: Union[_models2.NewlineDelimitedArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.NewlineDelimitedArrayProperty, _types_models2.NewlineDelimitedArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models2.NewlineDelimitedArrayProperty: """newline_delimited. - :param body: Is one of the following types: NewlineDelimitedArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.NewlineDelimitedArrayProperty or JSON or IO[bytes] + :param body: Is either a NewlineDelimitedArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.NewlineDelimitedArrayProperty or + ~encode.array.types.NewlineDelimitedArrayProperty or IO[bytes] :return: NewlineDelimitedArrayProperty. The NewlineDelimitedArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedArrayProperty @@ -765,12 +776,16 @@ def enum_comma_delimited( @overload def enum_comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.CommaDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.CommaDelimitedEnumArrayProperty: """enum_comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -798,13 +813,17 @@ def enum_comma_delimited( """ def enum_comma_delimited( - self, body: Union[_models2.CommaDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.CommaDelimitedEnumArrayProperty, _types_models2.CommaDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models2.CommaDelimitedEnumArrayProperty: """enum_comma_delimited. - :param body: Is one of the following types: CommaDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.CommaDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.CommaDelimitedEnumArrayProperty or + ~encode.array.types.CommaDelimitedEnumArrayProperty or IO[bytes] :return: CommaDelimitedEnumArrayProperty. The CommaDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedEnumArrayProperty @@ -886,12 +905,16 @@ def enum_space_delimited( @overload def enum_space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.SpaceDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.SpaceDelimitedEnumArrayProperty: """enum_space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -919,13 +942,17 @@ def enum_space_delimited( """ def enum_space_delimited( - self, body: Union[_models2.SpaceDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.SpaceDelimitedEnumArrayProperty, _types_models2.SpaceDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models2.SpaceDelimitedEnumArrayProperty: """enum_space_delimited. - :param body: Is one of the following types: SpaceDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.SpaceDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.SpaceDelimitedEnumArrayProperty or + ~encode.array.types.SpaceDelimitedEnumArrayProperty or IO[bytes] :return: SpaceDelimitedEnumArrayProperty. The SpaceDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedEnumArrayProperty @@ -1007,12 +1034,16 @@ def enum_pipe_delimited( @overload def enum_pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.PipeDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.PipeDelimitedEnumArrayProperty: """enum_pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1040,13 +1071,15 @@ def enum_pipe_delimited( """ def enum_pipe_delimited( - self, body: Union[_models2.PipeDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.PipeDelimitedEnumArrayProperty, _types_models2.PipeDelimitedEnumArrayProperty, IO[bytes]], + **kwargs: Any, ) -> _models2.PipeDelimitedEnumArrayProperty: """enum_pipe_delimited. - :param body: Is one of the following types: PipeDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.PipeDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.PipeDelimitedEnumArrayProperty or + ~encode.array.types.PipeDelimitedEnumArrayProperty or IO[bytes] :return: PipeDelimitedEnumArrayProperty. The PipeDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedEnumArrayProperty @@ -1128,12 +1161,16 @@ def enum_newline_delimited( @overload def enum_newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.NewlineDelimitedEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.NewlineDelimitedEnumArrayProperty: """enum_newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1161,13 +1198,17 @@ def enum_newline_delimited( """ def enum_newline_delimited( - self, body: Union[_models2.NewlineDelimitedEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.NewlineDelimitedEnumArrayProperty, _types_models2.NewlineDelimitedEnumArrayProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models2.NewlineDelimitedEnumArrayProperty: """enum_newline_delimited. - :param body: Is one of the following types: NewlineDelimitedEnumArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.array.models.NewlineDelimitedEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a NewlineDelimitedEnumArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.array.models.NewlineDelimitedEnumArrayProperty or + ~encode.array.types.NewlineDelimitedEnumArrayProperty or IO[bytes] :return: NewlineDelimitedEnumArrayProperty. The NewlineDelimitedEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedEnumArrayProperty @@ -1253,12 +1294,16 @@ def extensible_enum_comma_delimited( @overload def extensible_enum_comma_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.CommaDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.CommaDelimitedExtensibleEnumArrayProperty: """extensible_enum_comma_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.CommaDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1286,13 +1331,20 @@ def extensible_enum_comma_delimited( """ def extensible_enum_comma_delimited( - self, body: Union[_models2.CommaDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.CommaDelimitedExtensibleEnumArrayProperty, + _types_models2.CommaDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models2.CommaDelimitedExtensibleEnumArrayProperty: """extensible_enum_comma_delimited. - :param body: Is one of the following types: CommaDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a CommaDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.CommaDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: CommaDelimitedExtensibleEnumArrayProperty. The CommaDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.CommaDelimitedExtensibleEnumArrayProperty @@ -1378,12 +1430,16 @@ def extensible_enum_space_delimited( @overload def extensible_enum_space_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.SpaceDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.SpaceDelimitedExtensibleEnumArrayProperty: """extensible_enum_space_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.SpaceDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1411,13 +1467,20 @@ def extensible_enum_space_delimited( """ def extensible_enum_space_delimited( - self, body: Union[_models2.SpaceDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.SpaceDelimitedExtensibleEnumArrayProperty, + _types_models2.SpaceDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models2.SpaceDelimitedExtensibleEnumArrayProperty: """extensible_enum_space_delimited. - :param body: Is one of the following types: SpaceDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a SpaceDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.SpaceDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: SpaceDelimitedExtensibleEnumArrayProperty. The SpaceDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.SpaceDelimitedExtensibleEnumArrayProperty @@ -1503,12 +1566,16 @@ def extensible_enum_pipe_delimited( @overload def extensible_enum_pipe_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.PipeDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.PipeDelimitedExtensibleEnumArrayProperty: """extensible_enum_pipe_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.PipeDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1536,13 +1603,20 @@ def extensible_enum_pipe_delimited( """ def extensible_enum_pipe_delimited( - self, body: Union[_models2.PipeDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.PipeDelimitedExtensibleEnumArrayProperty, + _types_models2.PipeDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models2.PipeDelimitedExtensibleEnumArrayProperty: """extensible_enum_pipe_delimited. - :param body: Is one of the following types: PipeDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty or JSON or IO[bytes] + :param body: Is either a PipeDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.PipeDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: PipeDelimitedExtensibleEnumArrayProperty. The PipeDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.PipeDelimitedExtensibleEnumArrayProperty @@ -1628,12 +1702,16 @@ def extensible_enum_newline_delimited( @overload def extensible_enum_newline_delimited( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.NewlineDelimitedExtensibleEnumArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models2.NewlineDelimitedExtensibleEnumArrayProperty: """extensible_enum_newline_delimited. :param body: Required. - :type body: JSON + :type body: ~encode.array.types.NewlineDelimitedExtensibleEnumArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1661,14 +1739,20 @@ def extensible_enum_newline_delimited( """ def extensible_enum_newline_delimited( - self, body: Union[_models2.NewlineDelimitedExtensibleEnumArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.NewlineDelimitedExtensibleEnumArrayProperty, + _types_models2.NewlineDelimitedExtensibleEnumArrayProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models2.NewlineDelimitedExtensibleEnumArrayProperty: """extensible_enum_newline_delimited. - :param body: Is one of the following types: NewlineDelimitedExtensibleEnumArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty or JSON or - IO[bytes] + :param body: Is either a NewlineDelimitedExtensibleEnumArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty or + ~encode.array.types.NewlineDelimitedExtensibleEnumArrayProperty or IO[bytes] :return: NewlineDelimitedExtensibleEnumArrayProperty. The NewlineDelimitedExtensibleEnumArrayProperty is compatible with MutableMapping :rtype: ~encode.array.models.NewlineDelimitedExtensibleEnumArrayProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/types.py new file mode 100644 index 000000000000..2b15d1c99de2 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/encode/array/types.py @@ -0,0 +1,139 @@ +# coding=utf-8 + +from typing import TYPE_CHECKING, Union +from typing_extensions import Required, TypedDict + +if TYPE_CHECKING: + from .models import Colors, ColorsExtensibleEnum + + +class CommaDelimitedArrayProperty(TypedDict, total=False): + """CommaDelimitedArrayProperty. + + :ivar value: Required. + :vartype value: list[str] + """ + + value: Required[list[str]] + """Required.""" + + +class CommaDelimitedEnumArrayProperty(TypedDict, total=False): + """CommaDelimitedEnumArrayProperty. + + :ivar value: Required. + :vartype value: list[Union[str, "Colors"]] + """ + + value: Required[list[Union[str, "Colors"]]] + """Required.""" + + +class CommaDelimitedExtensibleEnumArrayProperty(TypedDict, total=False): # pylint: disable=name-too-long + """CommaDelimitedExtensibleEnumArrayProperty. + + :ivar value: Required. + :vartype value: list[Union[str, "ColorsExtensibleEnum"]] + """ + + value: Required[list[Union[str, "ColorsExtensibleEnum"]]] + """Required.""" + + +class NewlineDelimitedArrayProperty(TypedDict, total=False): + """NewlineDelimitedArrayProperty. + + :ivar value: Required. + :vartype value: list[str] + """ + + value: Required[list[str]] + """Required.""" + + +class NewlineDelimitedEnumArrayProperty(TypedDict, total=False): + """NewlineDelimitedEnumArrayProperty. + + :ivar value: Required. + :vartype value: list[Union[str, "Colors"]] + """ + + value: Required[list[Union[str, "Colors"]]] + """Required.""" + + +class NewlineDelimitedExtensibleEnumArrayProperty(TypedDict, total=False): # pylint: disable=name-too-long + """NewlineDelimitedExtensibleEnumArrayProperty. + + :ivar value: Required. + :vartype value: list[Union[str, "ColorsExtensibleEnum"]] + """ + + value: Required[list[Union[str, "ColorsExtensibleEnum"]]] + """Required.""" + + +class PipeDelimitedArrayProperty(TypedDict, total=False): + """PipeDelimitedArrayProperty. + + :ivar value: Required. + :vartype value: list[str] + """ + + value: Required[list[str]] + """Required.""" + + +class PipeDelimitedEnumArrayProperty(TypedDict, total=False): + """PipeDelimitedEnumArrayProperty. + + :ivar value: Required. + :vartype value: list[Union[str, "Colors"]] + """ + + value: Required[list[Union[str, "Colors"]]] + """Required.""" + + +class PipeDelimitedExtensibleEnumArrayProperty(TypedDict, total=False): + """PipeDelimitedExtensibleEnumArrayProperty. + + :ivar value: Required. + :vartype value: list[Union[str, "ColorsExtensibleEnum"]] + """ + + value: Required[list[Union[str, "ColorsExtensibleEnum"]]] + """Required.""" + + +class SpaceDelimitedArrayProperty(TypedDict, total=False): + """SpaceDelimitedArrayProperty. + + :ivar value: Required. + :vartype value: list[str] + """ + + value: Required[list[str]] + """Required.""" + + +class SpaceDelimitedEnumArrayProperty(TypedDict, total=False): + """SpaceDelimitedEnumArrayProperty. + + :ivar value: Required. + :vartype value: list[Union[str, "Colors"]] + """ + + value: Required[list[Union[str, "Colors"]]] + """Required.""" + + +class SpaceDelimitedExtensibleEnumArrayProperty(TypedDict, total=False): # pylint: disable=name-too-long + """SpaceDelimitedExtensibleEnumArrayProperty. + + :ivar value: Required. + :vartype value: list[Union[str, "ColorsExtensibleEnum"]] + """ + + value: Required[list[Union[str, "ColorsExtensibleEnum"]]] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/pyproject.toml index 8a2a14005ecb..faed3c5324ce 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-array/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/CHANGELOG.md new file mode 100644 index 000000000000..b957b2575b48 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (1970-01-01) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/MANIFEST.in b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/MANIFEST.in new file mode 100644 index 000000000000..882a33f4952b --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/MANIFEST.in @@ -0,0 +1,6 @@ +include *.md +include LICENSE +include encode/boolean/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include encode/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/README.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/__init__.py new file mode 100644 index 000000000000..31895d1b7f36 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import BooleanClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BooleanClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_client.py new file mode 100644 index 000000000000..00aaced6d3bb --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_client.py @@ -0,0 +1,87 @@ +# coding=utf-8 + +from copy import deepcopy +import sys +from typing import Any + +from corehttp.rest import HttpRequest, HttpResponse +from corehttp.runtime import PipelineClient, policies + +from ._configuration import BooleanClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .property.operations import PropertyOperations + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + + +class BooleanClient: # pylint: disable=client-accepts-api-version-keyword + """Test for encode decorator on boolean. + + :ivar property: PropertyOperations operations + :vartype property: encode.boolean.operations.PropertyOperations + :keyword endpoint: Service host. Default value is "http://localhost:3000". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "http://localhost:3000", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = BooleanClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.retry_policy, + self._config.authentication_policy, + self._config.logging_policy, + ] + self._client: PipelineClient = PipelineClient(endpoint=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.property = PropertyOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from corehttp.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~corehttp.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~corehttp.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_configuration.py new file mode 100644 index 000000000000..330d11526283 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_configuration.py @@ -0,0 +1,33 @@ +# coding=utf-8 + +from typing import Any + +from corehttp.runtime import policies + +from ._version import VERSION + + +class BooleanClientConfiguration: + """Configuration for BooleanClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "http://localhost:3000". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "encode-boolean/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_patch.py similarity index 99% rename from eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_operations/_patch.py rename to eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_utils/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_utils/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_utils/model_base.py new file mode 100644 index 000000000000..972617ba9ad8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_utils/model_base.py @@ -0,0 +1,1765 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +import isodate +from corehttp.exceptions import DeserializationError +from corehttp.utils import CaseInsensitiveEnumMeta +from corehttp.runtime.pipeline import PipelineResponse +from corehttp.serialization import _Null + +from corehttp.rest import HttpResponse + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on the mapping's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on the mapping's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: a set-like object providing a view on the mapping's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: The value for key if key is in the dictionary, else default. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if the dictionary is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from the dictionary. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Update the dictionary from a mapping or an iterable of key-value pairs. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: The value for key if key is in the dictionary, else default. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _serialize_duration(o, format) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass: dict[str, typing.Any] = {} + if args: + if isinstance(args[0], ET.Element): + dict_to_pass.update(self._init_from_xml(args[0])) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) + super().__init__(dict_to_pass) + + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + self, element: ET.Element + ) -> dict[str, typing.Any]: + """Deserialize an XML element into a dict mapping rest field names to values. + + :param ET.Element element: The XML element to deserialize from. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + existed_attr_keys: list[str] = [] + + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value.text if isinstance(value, ET.Element) else value) + except ValueError: + # for unknown value, return raw value + return value.text if isinstance(value, ET.Element) else value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +# pylint: disable=too-many-instance-attributes +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._is_optional = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + self._deserializer = deserializer + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + deserializer=deserializer, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) + wrapped_element = _create_xml_element( + element_name, + model_meta.get("prefix"), + _model_ns, + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + _set_xml_attribute(wrapped_element, k, v, prop_meta) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": _dict_ns, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": _items_ns, + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + _safe_register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_utils/serialization.py new file mode 100644 index 000000000000..4172d811ae21 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_utils/serialization.py @@ -0,0 +1,2169 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from corehttp.exceptions import DeserializationError, SerializationError +from corehttp.serialization import NULL as CoreNull + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_version.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_version.py new file mode 100644 index 000000000000..9f6458b8cdac --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/_version.py @@ -0,0 +1,3 @@ +# coding=utf-8 + +VERSION = "1.0.0b1" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/__init__.py new file mode 100644 index 000000000000..1f130cc84478 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import BooleanClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BooleanClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/_client.py new file mode 100644 index 000000000000..a8ecb3f0f187 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/_client.py @@ -0,0 +1,89 @@ +# coding=utf-8 + +from copy import deepcopy +import sys +from typing import Any, Awaitable + +from corehttp.rest import AsyncHttpResponse, HttpRequest +from corehttp.runtime import AsyncPipelineClient, policies + +from .._utils.serialization import Deserializer, Serializer +from ..property.aio.operations import PropertyOperations +from ._configuration import BooleanClientConfiguration + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + + +class BooleanClient: # pylint: disable=client-accepts-api-version-keyword + """Test for encode decorator on boolean. + + :ivar property: PropertyOperations operations + :vartype property: encode.boolean.aio.operations.PropertyOperations + :keyword endpoint: Service host. Default value is "http://localhost:3000". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "http://localhost:3000", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = BooleanClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.retry_policy, + self._config.authentication_policy, + self._config.logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(endpoint=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.property = PropertyOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from corehttp.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~corehttp.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~corehttp.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/_configuration.py new file mode 100644 index 000000000000..c5d5830a11de --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/_configuration.py @@ -0,0 +1,33 @@ +# coding=utf-8 + +from typing import Any + +from corehttp.runtime import policies + +from .._version import VERSION + + +class BooleanClientConfiguration: + """Configuration for BooleanClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "http://localhost:3000". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "encode-boolean/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/_patch.py similarity index 99% rename from eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_operations/_patch.py rename to eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/aio/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/operations/__init__.py new file mode 100644 index 000000000000..02fe504541c8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import PropertyOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PropertyOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/operations/_operations.py new file mode 100644 index 000000000000..d209b7467fb5 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/operations/_operations.py @@ -0,0 +1,520 @@ +# coding=utf-8 +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from corehttp.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from corehttp.rest import AsyncHttpResponse, HttpRequest +from corehttp.runtime import AsyncPipelineClient +from corehttp.runtime.pipeline import PipelineResponse +from corehttp.utils import case_insensitive_dict + +from ... import models as _models2, types as _types_models2 +from ...._utils.model_base import SdkJSONEncoder, _deserialize +from ...._utils.serialization import Deserializer, Serializer +from ....aio._configuration import BooleanClientConfiguration +from ...operations._operations import ( + build_property_false_lower_request, + build_property_false_mixed_request, + build_property_true_lower_request, + build_property_true_upper_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class PropertyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~encode.boolean.aio.BooleanClient`'s + :attr:`property` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: BooleanClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def true_lower( + self, value: _models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def true_lower( + self, value: _types_models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def true_lower( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def true_lower( + self, value: Union[_models2.BoolAsStringProperty, _types_models2.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_lower. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_true_lower_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models2.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def false_lower( + self, value: _models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def false_lower( + self, value: _types_models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def false_lower( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def false_lower( + self, value: Union[_models2.BoolAsStringProperty, _types_models2.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_lower. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_false_lower_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models2.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def true_upper( + self, value: _models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def true_upper( + self, value: _types_models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def true_upper( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def true_upper( + self, value: Union[_models2.BoolAsStringProperty, _types_models2.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """true_upper. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_true_upper_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models2.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def false_mixed( + self, value: _models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def false_mixed( + self, value: _types_models2.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def false_mixed( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def false_mixed( + self, value: Union[_models2.BoolAsStringProperty, _types_models2.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models2.BoolAsStringProperty: + """false_mixed. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models2.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_false_mixed_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models2.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/operations/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/aio/operations/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/models/__init__.py new file mode 100644 index 000000000000..c2e2c6530505 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/models/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + BoolAsStringProperty, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BoolAsStringProperty", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/models/_models.py new file mode 100644 index 000000000000..50a4e0b2fb49 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/models/_models.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# pylint: disable=useless-super-delegation + +from typing import Any, Mapping, overload + +from ..._utils.model_base import Model as _Model, rest_field + + +class BoolAsStringProperty(_Model): + """BoolAsStringProperty. + + :ivar value: Required. + :vartype value: bool + """ + + value: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + value: bool, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/models/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/models/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/operations/__init__.py new file mode 100644 index 000000000000..02fe504541c8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import PropertyOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PropertyOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/operations/_operations.py new file mode 100644 index 000000000000..3451ed1b8c03 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/operations/_operations.py @@ -0,0 +1,585 @@ +# coding=utf-8 +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from corehttp.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from corehttp.rest import HttpRequest, HttpResponse +from corehttp.runtime import PipelineClient +from corehttp.runtime.pipeline import PipelineResponse +from corehttp.utils import case_insensitive_dict + +from .. import models as _models1, types as _types_models1 +from ..._configuration import BooleanClientConfiguration +from ..._utils.model_base import SdkJSONEncoder, _deserialize +from ..._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_property_true_lower_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/encode/boolean/property/true-lower" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_property_false_lower_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/encode/boolean/property/false-lower" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_property_true_upper_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/encode/boolean/property/true-upper" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_property_false_mixed_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/encode/boolean/property/false-mixed" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +class PropertyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~encode.boolean.BooleanClient`'s + :attr:`property` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: BooleanClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def true_lower( + self, value: _models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def true_lower( + self, value: _types_models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def true_lower( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_lower. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def true_lower( + self, value: Union[_models1.BoolAsStringProperty, _types_models1.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_lower. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_true_lower_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models1.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def false_lower( + self, value: _models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def false_lower( + self, value: _types_models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def false_lower( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_lower. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def false_lower( + self, value: Union[_models1.BoolAsStringProperty, _types_models1.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_lower. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_false_lower_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models1.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def true_upper( + self, value: _models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def true_upper( + self, value: _types_models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def true_upper( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_upper. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def true_upper( + self, value: Union[_models1.BoolAsStringProperty, _types_models1.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """true_upper. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_true_upper_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models1.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def false_mixed( + self, value: _models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def false_mixed( + self, value: _types_models1.BoolAsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: ~encode.boolean.property.types.BoolAsStringProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def false_mixed( + self, value: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_mixed. + + :param value: Required. + :type value: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def false_mixed( + self, value: Union[_models1.BoolAsStringProperty, _types_models1.BoolAsStringProperty, IO[bytes]], **kwargs: Any + ) -> _models1.BoolAsStringProperty: + """false_mixed. + + :param value: Is either a BoolAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.boolean.property.models.BoolAsStringProperty or + ~encode.boolean.property.types.BoolAsStringProperty or IO[bytes] + :return: BoolAsStringProperty. The BoolAsStringProperty is compatible with MutableMapping + :rtype: ~encode.boolean.property.models.BoolAsStringProperty + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models1.BoolAsStringProperty] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(value, (IOBase, bytes)): + _content = value + else: + _content = json.dumps(value, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_property_false_mixed_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models1.BoolAsStringProperty, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/operations/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/operations/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/types.py new file mode 100644 index 000000000000..07783b6280d6 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/property/types.py @@ -0,0 +1,14 @@ +# coding=utf-8 + +from typing_extensions import Required, TypedDict + + +class BoolAsStringProperty(TypedDict, total=False): + """BoolAsStringProperty. + + :ivar value: Required. + :vartype value: bool + """ + + value: Required[bool] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/py.typed b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/encode/boolean/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/pyproject.toml new file mode 100644 index 000000000000..5cd04167043f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-boolean/pyproject.toml @@ -0,0 +1,50 @@ + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "encode-boolean" +authors = [ + { name = "" }, +] +description = " Encode Boolean Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", +] +requires-python = ">=3.10" + +dependencies = [ + "isodate>=0.6.1", + "corehttp[requests]>=1.0.0b6", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[tool.setuptools.dynamic] +version = {attr = "encode.boolean._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "encode", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/header/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/header/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/header/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/header/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/header/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/header/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/header/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/header/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/aio/operations/_operations.py index 7bacf1b854ec..fc87fc94ffda 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/aio/operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .... import models as _models3 +from .... import models as _models3, types as _types_models3 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import BytesClientConfiguration @@ -30,7 +30,6 @@ build_property_default_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -70,12 +69,12 @@ async def default( @overload async def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.DefaultBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.DefaultBytesProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.DefaultBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -101,12 +100,13 @@ async def default( """ async def default( - self, body: Union[_models3.DefaultBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models3.DefaultBytesProperty, _types_models3.DefaultBytesProperty, IO[bytes]], **kwargs: Any ) -> _models3.DefaultBytesProperty: """default. - :param body: Is one of the following types: DefaultBytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.DefaultBytesProperty or JSON or IO[bytes] + :param body: Is either a DefaultBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.DefaultBytesProperty or + ~encode.bytes.types.DefaultBytesProperty or IO[bytes] :return: DefaultBytesProperty. The DefaultBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.DefaultBytesProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -186,12 +186,12 @@ async def base64( @overload async def base64( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.Base64BytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.Base64BytesProperty: """base64. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -217,12 +217,13 @@ async def base64( """ async def base64( - self, body: Union[_models3.Base64BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models3.Base64BytesProperty, _types_models3.Base64BytesProperty, IO[bytes]], **kwargs: Any ) -> _models3.Base64BytesProperty: """base64. - :param body: Is one of the following types: Base64BytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.Base64BytesProperty or JSON or IO[bytes] + :param body: Is either a Base64BytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64BytesProperty or ~encode.bytes.types.Base64BytesProperty + or IO[bytes] :return: Base64BytesProperty. The Base64BytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64BytesProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -302,12 +303,12 @@ async def base64_url( @overload async def base64_url( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.Base64urlBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.Base64urlBytesProperty: """base64_url. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64urlBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -333,12 +334,15 @@ async def base64_url( """ async def base64_url( - self, body: Union[_models3.Base64urlBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.Base64urlBytesProperty, _types_models3.Base64urlBytesProperty, IO[bytes]], + **kwargs: Any ) -> _models3.Base64urlBytesProperty: """base64_url. - :param body: Is one of the following types: Base64urlBytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.Base64urlBytesProperty or JSON or IO[bytes] + :param body: Is either a Base64urlBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64urlBytesProperty or + ~encode.bytes.types.Base64urlBytesProperty or IO[bytes] :return: Base64urlBytesProperty. The Base64urlBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64urlBytesProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -419,12 +423,12 @@ async def base64_url_array( @overload async def base64_url_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.Base64urlArrayBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.Base64urlArrayBytesProperty: """base64_url_array. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64urlArrayBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -452,13 +456,15 @@ async def base64_url_array( """ async def base64_url_array( - self, body: Union[_models3.Base64urlArrayBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.Base64urlArrayBytesProperty, _types_models3.Base64urlArrayBytesProperty, IO[bytes]], + **kwargs: Any ) -> _models3.Base64urlArrayBytesProperty: """base64_url_array. - :param body: Is one of the following types: Base64urlArrayBytesProperty, JSON, IO[bytes] - Required. - :type body: ~encode.bytes.models.Base64urlArrayBytesProperty or JSON or IO[bytes] + :param body: Is either a Base64urlArrayBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64urlArrayBytesProperty or + ~encode.bytes.types.Base64urlArrayBytesProperty or IO[bytes] :return: Base64urlArrayBytesProperty. The Base64urlArrayBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64urlArrayBytesProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/operations/_operations.py index 7deb0250bd9e..97c15482dfd3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/operations/_operations.py @@ -19,12 +19,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..._configuration import BytesClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -135,12 +134,12 @@ def default( @overload def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.DefaultBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.DefaultBytesProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.DefaultBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -166,12 +165,13 @@ def default( """ def default( - self, body: Union[_models2.DefaultBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models2.DefaultBytesProperty, _types_models2.DefaultBytesProperty, IO[bytes]], **kwargs: Any ) -> _models2.DefaultBytesProperty: """default. - :param body: Is one of the following types: DefaultBytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.DefaultBytesProperty or JSON or IO[bytes] + :param body: Is either a DefaultBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.DefaultBytesProperty or + ~encode.bytes.types.DefaultBytesProperty or IO[bytes] :return: DefaultBytesProperty. The DefaultBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.DefaultBytesProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -251,12 +251,12 @@ def base64( @overload def base64( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Base64BytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Base64BytesProperty: """base64. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -282,12 +282,13 @@ def base64( """ def base64( - self, body: Union[_models2.Base64BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models2.Base64BytesProperty, _types_models2.Base64BytesProperty, IO[bytes]], **kwargs: Any ) -> _models2.Base64BytesProperty: """base64. - :param body: Is one of the following types: Base64BytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.Base64BytesProperty or JSON or IO[bytes] + :param body: Is either a Base64BytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64BytesProperty or ~encode.bytes.types.Base64BytesProperty + or IO[bytes] :return: Base64BytesProperty. The Base64BytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64BytesProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -367,12 +368,12 @@ def base64_url( @overload def base64_url( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Base64urlBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Base64urlBytesProperty: """base64_url. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64urlBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -398,12 +399,15 @@ def base64_url( """ def base64_url( - self, body: Union[_models2.Base64urlBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.Base64urlBytesProperty, _types_models2.Base64urlBytesProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Base64urlBytesProperty: """base64_url. - :param body: Is one of the following types: Base64urlBytesProperty, JSON, IO[bytes] Required. - :type body: ~encode.bytes.models.Base64urlBytesProperty or JSON or IO[bytes] + :param body: Is either a Base64urlBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64urlBytesProperty or + ~encode.bytes.types.Base64urlBytesProperty or IO[bytes] :return: Base64urlBytesProperty. The Base64urlBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64urlBytesProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -484,12 +488,12 @@ def base64_url_array( @overload def base64_url_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Base64urlArrayBytesProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Base64urlArrayBytesProperty: """base64_url_array. :param body: Required. - :type body: JSON + :type body: ~encode.bytes.types.Base64urlArrayBytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -517,13 +521,15 @@ def base64_url_array( """ def base64_url_array( - self, body: Union[_models2.Base64urlArrayBytesProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.Base64urlArrayBytesProperty, _types_models2.Base64urlArrayBytesProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Base64urlArrayBytesProperty: """base64_url_array. - :param body: Is one of the following types: Base64urlArrayBytesProperty, JSON, IO[bytes] - Required. - :type body: ~encode.bytes.models.Base64urlArrayBytesProperty or JSON or IO[bytes] + :param body: Is either a Base64urlArrayBytesProperty type or a IO[bytes] type. Required. + :type body: ~encode.bytes.models.Base64urlArrayBytesProperty or + ~encode.bytes.types.Base64urlArrayBytesProperty or IO[bytes] :return: Base64urlArrayBytesProperty. The Base64urlArrayBytesProperty is compatible with MutableMapping :rtype: ~encode.bytes.models.Base64urlArrayBytesProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/property/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/query/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/query/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/query/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/query/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/query/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/query/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/query/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/query/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/requestbody/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/requestbody/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/requestbody/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/requestbody/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/requestbody/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/requestbody/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/requestbody/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/requestbody/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/responsebody/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/responsebody/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/responsebody/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/responsebody/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/responsebody/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/responsebody/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/responsebody/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/responsebody/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/types.py index a8518fe09755..c1629ebadc0c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/encode/bytes/types.py @@ -7,10 +7,10 @@ class Base64BytesProperty(TypedDict, total=False): """Base64BytesProperty. :ivar value: Required. - :vartype value: bytes + :vartype value: str """ - value: Required[bytes] + value: Required[str] """Required.""" @@ -18,10 +18,10 @@ class Base64urlArrayBytesProperty(TypedDict, total=False): """Base64urlArrayBytesProperty. :ivar value: Required. - :vartype value: list[bytes] + :vartype value: list[str] """ - value: Required[list[bytes]] + value: Required[list[str]] """Required.""" @@ -29,10 +29,10 @@ class Base64urlBytesProperty(TypedDict, total=False): """Base64urlBytesProperty. :ivar value: Required. - :vartype value: bytes + :vartype value: str """ - value: Required[bytes] + value: Required[str] """Required.""" @@ -40,8 +40,8 @@ class DefaultBytesProperty(TypedDict, total=False): """DefaultBytesProperty. :ivar value: Required. - :vartype value: bytes + :vartype value: str """ - value: Required[bytes] + value: Required[str] """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/pyproject.toml index 6e72db998ef6..05b195dc1b1e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-bytes/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/header/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/header/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/header/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/header/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/header/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/header/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/header/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/header/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/aio/operations/_operations.py index 7114100717e7..d8b1caa2411d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/aio/operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .... import models as _models3 +from .... import models as _models3, types as _types_models3 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import DatetimeClientConfiguration @@ -31,7 +31,6 @@ build_property_unix_timestamp_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -71,12 +70,12 @@ async def default( @overload async def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.DefaultDatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.DefaultDatetimeProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.DefaultDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -102,12 +101,15 @@ async def default( """ async def default( - self, body: Union[_models3.DefaultDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.DefaultDatetimeProperty, _types_models3.DefaultDatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models3.DefaultDatetimeProperty: """default. - :param body: Is one of the following types: DefaultDatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.DefaultDatetimeProperty or JSON or IO[bytes] + :param body: Is either a DefaultDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.DefaultDatetimeProperty or + ~encode.datetime.types.DefaultDatetimeProperty or IO[bytes] :return: DefaultDatetimeProperty. The DefaultDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.DefaultDatetimeProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -187,12 +189,12 @@ async def rfc3339( @overload async def rfc3339( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.Rfc3339DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.Rfc3339DatetimeProperty: """rfc3339. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.Rfc3339DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -218,12 +220,15 @@ async def rfc3339( """ async def rfc3339( - self, body: Union[_models3.Rfc3339DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.Rfc3339DatetimeProperty, _types_models3.Rfc3339DatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models3.Rfc3339DatetimeProperty: """rfc3339. - :param body: Is one of the following types: Rfc3339DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.Rfc3339DatetimeProperty or JSON or IO[bytes] + :param body: Is either a Rfc3339DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.Rfc3339DatetimeProperty or + ~encode.datetime.types.Rfc3339DatetimeProperty or IO[bytes] :return: Rfc3339DatetimeProperty. The Rfc3339DatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.Rfc3339DatetimeProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -303,12 +308,12 @@ async def rfc7231( @overload async def rfc7231( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models3.Rfc7231DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models3.Rfc7231DatetimeProperty: """rfc7231. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.Rfc7231DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -334,12 +339,15 @@ async def rfc7231( """ async def rfc7231( - self, body: Union[_models3.Rfc7231DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.Rfc7231DatetimeProperty, _types_models3.Rfc7231DatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models3.Rfc7231DatetimeProperty: """rfc7231. - :param body: Is one of the following types: Rfc7231DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.Rfc7231DatetimeProperty or JSON or IO[bytes] + :param body: Is either a Rfc7231DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.Rfc7231DatetimeProperty or + ~encode.datetime.types.Rfc7231DatetimeProperty or IO[bytes] :return: Rfc7231DatetimeProperty. The Rfc7231DatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.Rfc7231DatetimeProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -420,12 +428,16 @@ async def unix_timestamp( @overload async def unix_timestamp( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.UnixTimestampDatetimeProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.UnixTimestampDatetimeProperty: """unix_timestamp. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.UnixTimestampDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -453,13 +465,15 @@ async def unix_timestamp( """ async def unix_timestamp( - self, body: Union[_models3.UnixTimestampDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models3.UnixTimestampDatetimeProperty, _types_models3.UnixTimestampDatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models3.UnixTimestampDatetimeProperty: """unix_timestamp. - :param body: Is one of the following types: UnixTimestampDatetimeProperty, JSON, IO[bytes] - Required. - :type body: ~encode.datetime.models.UnixTimestampDatetimeProperty or JSON or IO[bytes] + :param body: Is either a UnixTimestampDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.UnixTimestampDatetimeProperty or + ~encode.datetime.types.UnixTimestampDatetimeProperty or IO[bytes] :return: UnixTimestampDatetimeProperty. The UnixTimestampDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.UnixTimestampDatetimeProperty @@ -545,12 +559,16 @@ async def unix_timestamp_array( @overload async def unix_timestamp_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models3.UnixTimestampArrayDatetimeProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models3.UnixTimestampArrayDatetimeProperty: """unix_timestamp_array. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.UnixTimestampArrayDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -578,13 +596,17 @@ async def unix_timestamp_array( """ async def unix_timestamp_array( - self, body: Union[_models3.UnixTimestampArrayDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models3.UnixTimestampArrayDatetimeProperty, _types_models3.UnixTimestampArrayDatetimeProperty, IO[bytes] + ], + **kwargs: Any ) -> _models3.UnixTimestampArrayDatetimeProperty: """unix_timestamp_array. - :param body: Is one of the following types: UnixTimestampArrayDatetimeProperty, JSON, IO[bytes] - Required. - :type body: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty or JSON or IO[bytes] + :param body: Is either a UnixTimestampArrayDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty or + ~encode.datetime.types.UnixTimestampArrayDatetimeProperty or IO[bytes] :return: UnixTimestampArrayDatetimeProperty. The UnixTimestampArrayDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/operations/_operations.py index 459106fc08f5..d58aec549596 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/operations/_operations.py @@ -19,12 +19,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..._configuration import DatetimeClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -152,12 +151,12 @@ def default( @overload def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.DefaultDatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.DefaultDatetimeProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.DefaultDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -183,12 +182,15 @@ def default( """ def default( - self, body: Union[_models2.DefaultDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.DefaultDatetimeProperty, _types_models2.DefaultDatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models2.DefaultDatetimeProperty: """default. - :param body: Is one of the following types: DefaultDatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.DefaultDatetimeProperty or JSON or IO[bytes] + :param body: Is either a DefaultDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.DefaultDatetimeProperty or + ~encode.datetime.types.DefaultDatetimeProperty or IO[bytes] :return: DefaultDatetimeProperty. The DefaultDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.DefaultDatetimeProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -268,12 +270,12 @@ def rfc3339( @overload def rfc3339( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Rfc3339DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Rfc3339DatetimeProperty: """rfc3339. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.Rfc3339DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -299,12 +301,15 @@ def rfc3339( """ def rfc3339( - self, body: Union[_models2.Rfc3339DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.Rfc3339DatetimeProperty, _types_models2.Rfc3339DatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Rfc3339DatetimeProperty: """rfc3339. - :param body: Is one of the following types: Rfc3339DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.Rfc3339DatetimeProperty or JSON or IO[bytes] + :param body: Is either a Rfc3339DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.Rfc3339DatetimeProperty or + ~encode.datetime.types.Rfc3339DatetimeProperty or IO[bytes] :return: Rfc3339DatetimeProperty. The Rfc3339DatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.Rfc3339DatetimeProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -384,12 +389,12 @@ def rfc7231( @overload def rfc7231( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Rfc7231DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Rfc7231DatetimeProperty: """rfc7231. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.Rfc7231DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -415,12 +420,15 @@ def rfc7231( """ def rfc7231( - self, body: Union[_models2.Rfc7231DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.Rfc7231DatetimeProperty, _types_models2.Rfc7231DatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Rfc7231DatetimeProperty: """rfc7231. - :param body: Is one of the following types: Rfc7231DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~encode.datetime.models.Rfc7231DatetimeProperty or JSON or IO[bytes] + :param body: Is either a Rfc7231DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.Rfc7231DatetimeProperty or + ~encode.datetime.types.Rfc7231DatetimeProperty or IO[bytes] :return: Rfc7231DatetimeProperty. The Rfc7231DatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.Rfc7231DatetimeProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -501,12 +509,16 @@ def unix_timestamp( @overload def unix_timestamp( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.UnixTimestampDatetimeProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.UnixTimestampDatetimeProperty: """unix_timestamp. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.UnixTimestampDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -534,13 +546,15 @@ def unix_timestamp( """ def unix_timestamp( - self, body: Union[_models2.UnixTimestampDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.UnixTimestampDatetimeProperty, _types_models2.UnixTimestampDatetimeProperty, IO[bytes]], + **kwargs: Any ) -> _models2.UnixTimestampDatetimeProperty: """unix_timestamp. - :param body: Is one of the following types: UnixTimestampDatetimeProperty, JSON, IO[bytes] - Required. - :type body: ~encode.datetime.models.UnixTimestampDatetimeProperty or JSON or IO[bytes] + :param body: Is either a UnixTimestampDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.UnixTimestampDatetimeProperty or + ~encode.datetime.types.UnixTimestampDatetimeProperty or IO[bytes] :return: UnixTimestampDatetimeProperty. The UnixTimestampDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.UnixTimestampDatetimeProperty @@ -626,12 +640,16 @@ def unix_timestamp_array( @overload def unix_timestamp_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.UnixTimestampArrayDatetimeProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.UnixTimestampArrayDatetimeProperty: """unix_timestamp_array. :param body: Required. - :type body: JSON + :type body: ~encode.datetime.types.UnixTimestampArrayDatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -659,13 +677,17 @@ def unix_timestamp_array( """ def unix_timestamp_array( - self, body: Union[_models2.UnixTimestampArrayDatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.UnixTimestampArrayDatetimeProperty, _types_models2.UnixTimestampArrayDatetimeProperty, IO[bytes] + ], + **kwargs: Any ) -> _models2.UnixTimestampArrayDatetimeProperty: """unix_timestamp_array. - :param body: Is one of the following types: UnixTimestampArrayDatetimeProperty, JSON, IO[bytes] - Required. - :type body: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty or JSON or IO[bytes] + :param body: Is either a UnixTimestampArrayDatetimeProperty type or a IO[bytes] type. Required. + :type body: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty or + ~encode.datetime.types.UnixTimestampArrayDatetimeProperty or IO[bytes] :return: UnixTimestampArrayDatetimeProperty. The UnixTimestampArrayDatetimeProperty is compatible with MutableMapping :rtype: ~encode.datetime.models.UnixTimestampArrayDatetimeProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/property/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/query/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/query/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/query/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/query/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/query/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/query/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/query/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/query/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/responseheader/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/responseheader/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/responseheader/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/responseheader/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/responseheader/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/responseheader/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/responseheader/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/responseheader/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/types.py index 0725a7d3a02e..e16715eff9cc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/encode/datetime/types.py @@ -1,6 +1,5 @@ # coding=utf-8 -import datetime from typing_extensions import Required, TypedDict @@ -8,10 +7,10 @@ class DefaultDatetimeProperty(TypedDict, total=False): """DefaultDatetimeProperty. :ivar value: Required. - :vartype value: ~datetime.datetime + :vartype value: str """ - value: Required[datetime.datetime] + value: Required[str] """Required.""" @@ -19,10 +18,10 @@ class Rfc3339DatetimeProperty(TypedDict, total=False): """Rfc3339DatetimeProperty. :ivar value: Required. - :vartype value: ~datetime.datetime + :vartype value: str """ - value: Required[datetime.datetime] + value: Required[str] """Required.""" @@ -30,10 +29,10 @@ class Rfc7231DatetimeProperty(TypedDict, total=False): """Rfc7231DatetimeProperty. :ivar value: Required. - :vartype value: ~datetime.datetime + :vartype value: str """ - value: Required[datetime.datetime] + value: Required[str] """Required.""" @@ -41,10 +40,10 @@ class UnixTimestampArrayDatetimeProperty(TypedDict, total=False): """UnixTimestampArrayDatetimeProperty. :ivar value: Required. - :vartype value: list[~datetime.datetime] + :vartype value: list[int] """ - value: Required[list[datetime.datetime]] + value: Required[list[int]] """Required.""" @@ -52,8 +51,8 @@ class UnixTimestampDatetimeProperty(TypedDict, total=False): """UnixTimestampDatetimeProperty. :ivar value: Required. - :vartype value: ~datetime.datetime + :vartype value: int """ - value: Required[datetime.datetime] + value: Required[int] """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/pyproject.toml index b54be7c6b7a1..5098eec504c1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-datetime/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_client.py index 2deedb900db8..07146f6169a0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_client.py @@ -10,6 +10,7 @@ from ._configuration import DurationClientConfiguration from ._utils.serialization import Deserializer, Serializer from .header.operations import HeaderOperations +from .operations import LossyOperations from .property.operations import PropertyOperations from .query.operations import QueryOperations @@ -28,6 +29,8 @@ class DurationClient: # pylint: disable=client-accepts-api-version-keyword :vartype property: encode.duration.operations.PropertyOperations :ivar header: HeaderOperations operations :vartype header: encode.duration.operations.HeaderOperations + :ivar lossy: LossyOperations operations + :vartype lossy: encode.duration.operations.LossyOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -57,6 +60,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) self.property = PropertyOperations(self._client, self._config, self._serialize, self._deserialize) self.header = HeaderOperations(self._client, self._config, self._serialize, self._deserialize) + self.lossy = LossyOperations(self._client, self._config, self._serialize, self._deserialize) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/_client.py index d5ce7657a04e..3339895c2ca7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/_client.py @@ -12,6 +12,7 @@ from ..property.aio.operations import PropertyOperations from ..query.aio.operations import QueryOperations from ._configuration import DurationClientConfiguration +from .operations import LossyOperations if sys.version_info >= (3, 11): from typing import Self @@ -28,6 +29,8 @@ class DurationClient: # pylint: disable=client-accepts-api-version-keyword :vartype property: encode.duration.aio.operations.PropertyOperations :ivar header: HeaderOperations operations :vartype header: encode.duration.aio.operations.HeaderOperations + :ivar lossy: LossyOperations operations + :vartype lossy: encode.duration.aio.operations.LossyOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -57,6 +60,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) self.property = PropertyOperations(self._client, self._config, self._serialize, self._deserialize) self.header = HeaderOperations(self._client, self._config, self._serialize, self._deserialize) + self.lossy = LossyOperations(self._client, self._config, self._serialize, self._deserialize) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/operations/__init__.py new file mode 100644 index 000000000000..36b5956b10c7 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import LossyOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "LossyOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/operations/_operations.py new file mode 100644 index 000000000000..557dc90241f3 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/operations/_operations.py @@ -0,0 +1,129 @@ +# coding=utf-8 +from collections.abc import MutableMapping +import datetime +from typing import Any, Callable, Optional, TypeVar + +from corehttp.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from corehttp.rest import AsyncHttpResponse, HttpRequest +from corehttp.runtime import AsyncPipelineClient +from corehttp.runtime.pipeline import PipelineResponse + +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import build_lossy_int_milliseconds_request, build_lossy_int_seconds_request +from .._configuration import DurationClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class LossyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~encode.duration.aio.DurationClient`'s + :attr:`lossy` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: DurationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def int_seconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: + """int_seconds. + + :keyword input: Required. + :paramtype input: ~datetime.timedelta + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_lossy_int_seconds_request( + input=input, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + async def int_milliseconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: + """int_milliseconds. + + :keyword input: Required. + :paramtype input: ~datetime.timedelta + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_lossy_int_milliseconds_request( + input=input, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/operations/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/aio/operations/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/aio/operations/_operations.py index 9330358873e2..10780d132279 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/aio/operations/_operations.py @@ -187,11 +187,11 @@ async def iso8601_array(self, *, duration: list[datetime.timedelta], **kwargs: A if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_seconds(self, *, duration: int, **kwargs: Any) -> None: + async def int32_seconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """int32_seconds. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -231,11 +231,11 @@ async def int32_seconds(self, *, duration: int, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_seconds_larger_unit(self, *, duration: int, **kwargs: Any) -> None: + async def int32_seconds_larger_unit(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """int32_seconds_larger_unit. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -275,11 +275,11 @@ async def int32_seconds_larger_unit(self, *, duration: int, **kwargs: Any) -> No if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float_seconds(self, *, duration: float, **kwargs: Any) -> None: + async def float_seconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float_seconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -319,11 +319,11 @@ async def float_seconds(self, *, duration: float, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float_seconds_larger_unit(self, *, duration: float, **kwargs: Any) -> None: + async def float_seconds_larger_unit(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float_seconds_larger_unit. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -363,11 +363,11 @@ async def float_seconds_larger_unit(self, *, duration: float, **kwargs: Any) -> if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float64_seconds(self, *, duration: float, **kwargs: Any) -> None: + async def float64_seconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float64_seconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -407,11 +407,11 @@ async def float64_seconds(self, *, duration: float, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_milliseconds(self, *, duration: int, **kwargs: Any) -> None: + async def int32_milliseconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """int32_milliseconds. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -451,11 +451,11 @@ async def int32_milliseconds(self, *, duration: int, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_milliseconds_larger_unit(self, *, duration: int, **kwargs: Any) -> None: + async def int32_milliseconds_larger_unit(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """int32_milliseconds_larger_unit. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -495,11 +495,11 @@ async def int32_milliseconds_larger_unit(self, *, duration: int, **kwargs: Any) if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float_milliseconds(self, *, duration: float, **kwargs: Any) -> None: + async def float_milliseconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float_milliseconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -539,11 +539,11 @@ async def float_milliseconds(self, *, duration: float, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float_milliseconds_larger_unit(self, *, duration: float, **kwargs: Any) -> None: + async def float_milliseconds_larger_unit(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float_milliseconds_larger_unit. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -583,11 +583,11 @@ async def float_milliseconds_larger_unit(self, *, duration: float, **kwargs: Any if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float64_milliseconds(self, *, duration: float, **kwargs: Any) -> None: + async def float64_milliseconds(self, *, duration: datetime.timedelta, **kwargs: Any) -> None: """float64_milliseconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -627,11 +627,11 @@ async def float64_milliseconds(self, *, duration: float, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_milliseconds_array(self, *, duration: list[int], **kwargs: Any) -> None: + async def int32_milliseconds_array(self, *, duration: list[datetime.timedelta], **kwargs: Any) -> None: """int32_milliseconds_array. :keyword duration: Required. - :paramtype duration: list[int] + :paramtype duration: list[~datetime.timedelta] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/operations/_operations.py index 2b55253d6bc8..72dc59bdf81e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/operations/_operations.py @@ -62,20 +62,20 @@ def build_header_iso8601_array_request(*, duration: list[datetime.timedelta], ** return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_header_int32_seconds_request(*, duration: int, **kwargs: Any) -> HttpRequest: +def build_header_int32_seconds_request(*, duration: datetime.timedelta, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) # Construct URL _url = "/encode/duration/header/int32-seconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "int") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-seconds-int") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_int32_seconds_larger_unit_request( # pylint: disable=name-too-long - *, duration: int, **kwargs: Any + *, duration: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -83,25 +83,25 @@ def build_header_int32_seconds_larger_unit_request( # pylint: disable=name-too- _url = "/encode/duration/header/int32-seconds-larger-unit" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "int") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-seconds-int") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_header_float_seconds_request(*, duration: float, **kwargs: Any) -> HttpRequest: +def build_header_float_seconds_request(*, duration: datetime.timedelta, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) # Construct URL _url = "/encode/duration/header/float-seconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-seconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_float_seconds_larger_unit_request( # pylint: disable=name-too-long - *, duration: float, **kwargs: Any + *, duration: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -109,37 +109,37 @@ def build_header_float_seconds_larger_unit_request( # pylint: disable=name-too- _url = "/encode/duration/header/float-seconds-larger-unit" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-seconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_header_float64_seconds_request(*, duration: float, **kwargs: Any) -> HttpRequest: +def build_header_float64_seconds_request(*, duration: datetime.timedelta, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) # Construct URL _url = "/encode/duration/header/float64-seconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-seconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_header_int32_milliseconds_request(*, duration: int, **kwargs: Any) -> HttpRequest: +def build_header_int32_milliseconds_request(*, duration: datetime.timedelta, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) # Construct URL _url = "/encode/duration/header/int32-milliseconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "int") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-milliseconds-int") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_int32_milliseconds_larger_unit_request( # pylint: disable=name-too-long - *, duration: int, **kwargs: Any + *, duration: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -147,25 +147,25 @@ def build_header_int32_milliseconds_larger_unit_request( # pylint: disable=name _url = "/encode/duration/header/int32-milliseconds-larger-unit" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "int") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-milliseconds-int") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_header_float_milliseconds_request(*, duration: float, **kwargs: Any) -> HttpRequest: +def build_header_float_milliseconds_request(*, duration: datetime.timedelta, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) # Construct URL _url = "/encode/duration/header/float-milliseconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_float_milliseconds_larger_unit_request( # pylint: disable=name-too-long - *, duration: float, **kwargs: Any + *, duration: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -173,13 +173,13 @@ def build_header_float_milliseconds_larger_unit_request( # pylint: disable=name _url = "/encode/duration/header/float-milliseconds-larger-unit" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_float64_milliseconds_request( # pylint: disable=name-too-long - *, duration: float, **kwargs: Any + *, duration: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -187,13 +187,13 @@ def build_header_float64_milliseconds_request( # pylint: disable=name-too-long _url = "/encode/duration/header/float64-milliseconds" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "float") + _headers["duration"] = _SERIALIZER.header("duration", duration, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) def build_header_int32_milliseconds_array_request( # pylint: disable=name-too-long - *, duration: list[int], **kwargs: Any + *, duration: list[datetime.timedelta], **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -201,7 +201,7 @@ def build_header_int32_milliseconds_array_request( # pylint: disable=name-too-l _url = "/encode/duration/header/int32-milliseconds-array" # Construct headers - _headers["duration"] = _SERIALIZER.header("duration", duration, "[int]", div=",") + _headers["duration"] = _SERIALIZER.header("duration", duration, "[duration-milliseconds-int]", div=",") return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) @@ -361,11 +361,13 @@ def iso8601_array( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) # type: ignore - def int32_seconds(self, *, duration: int, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + def int32_seconds( # pylint: disable=inconsistent-return-statements + self, *, duration: datetime.timedelta, **kwargs: Any + ) -> None: """int32_seconds. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -406,12 +408,12 @@ def int32_seconds(self, *, duration: int, **kwargs: Any) -> None: # pylint: dis return cls(pipeline_response, None, {}) # type: ignore def int32_seconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, duration: int, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """int32_seconds_larger_unit. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -452,12 +454,12 @@ def int32_seconds_larger_unit( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def float_seconds( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float_seconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -498,12 +500,12 @@ def float_seconds( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def float_seconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float_seconds_larger_unit. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -544,12 +546,12 @@ def float_seconds_larger_unit( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def float64_seconds( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float64_seconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -590,12 +592,12 @@ def float64_seconds( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def int32_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, duration: int, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """int32_milliseconds. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -636,12 +638,12 @@ def int32_milliseconds( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def int32_milliseconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, duration: int, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """int32_milliseconds_larger_unit. :keyword duration: Required. - :paramtype duration: int + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -682,12 +684,12 @@ def int32_milliseconds_larger_unit( # pylint: disable=inconsistent-return-state return cls(pipeline_response, None, {}) # type: ignore def float_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float_milliseconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -728,12 +730,12 @@ def float_milliseconds( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def float_milliseconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float_milliseconds_larger_unit. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -774,12 +776,12 @@ def float_milliseconds_larger_unit( # pylint: disable=inconsistent-return-state return cls(pipeline_response, None, {}) # type: ignore def float64_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, duration: float, **kwargs: Any + self, *, duration: datetime.timedelta, **kwargs: Any ) -> None: """float64_milliseconds. :keyword duration: Required. - :paramtype duration: float + :paramtype duration: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -820,12 +822,12 @@ def float64_milliseconds( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def int32_milliseconds_array( # pylint: disable=inconsistent-return-statements - self, *, duration: list[int], **kwargs: Any + self, *, duration: list[datetime.timedelta], **kwargs: Any ) -> None: """int32_milliseconds_array. :keyword duration: Required. - :paramtype duration: list[int] + :paramtype duration: list[~datetime.timedelta] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/header/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/operations/__init__.py new file mode 100644 index 000000000000..36b5956b10c7 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import LossyOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "LossyOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/operations/_operations.py new file mode 100644 index 000000000000..45ed47698204 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/operations/_operations.py @@ -0,0 +1,160 @@ +# coding=utf-8 +from collections.abc import MutableMapping +import datetime +from typing import Any, Callable, Optional, TypeVar + +from corehttp.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from corehttp.rest import HttpRequest, HttpResponse +from corehttp.runtime import PipelineClient +from corehttp.runtime.pipeline import PipelineResponse +from corehttp.utils import case_insensitive_dict + +from .._configuration import DurationClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_lossy_int_seconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/encode/duration/lossy/int32-seconds" + + # Construct parameters + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-int") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + +def build_lossy_int_milliseconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/encode/duration/lossy/int32-milliseconds" + + # Construct parameters + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-int") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + +class LossyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~encode.duration.DurationClient`'s + :attr:`lossy` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: DurationClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def int_seconds( # pylint: disable=inconsistent-return-statements + self, *, input: datetime.timedelta, **kwargs: Any + ) -> None: + """int_seconds. + + :keyword input: Required. + :paramtype input: ~datetime.timedelta + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_lossy_int_seconds_request( + input=input, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + def int_milliseconds( # pylint: disable=inconsistent-return-statements + self, *, input: datetime.timedelta, **kwargs: Any + ) -> None: + """int_milliseconds. + + :keyword input: Required. + :paramtype input: ~datetime.timedelta + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_lossy_int_milliseconds_request( + input=input, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/operations/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/operations/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/aio/operations/_operations.py index ce3573f011ff..0a5bd482c6a8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/aio/operations/_operations.py @@ -20,7 +20,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import DurationClientConfiguration @@ -41,7 +41,6 @@ build_property_iso8601_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -81,12 +80,12 @@ async def default( @overload async def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.DefaultDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.DefaultDurationProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.DefaultDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -112,12 +111,15 @@ async def default( """ async def default( - self, body: Union[_models2.DefaultDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.DefaultDurationProperty, _types_models2.DefaultDurationProperty, IO[bytes]], + **kwargs: Any ) -> _models2.DefaultDurationProperty: """default. - :param body: Is one of the following types: DefaultDurationProperty, JSON, IO[bytes] Required. - :type body: ~encode.duration.property.models.DefaultDurationProperty or JSON or IO[bytes] + :param body: Is either a DefaultDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.DefaultDurationProperty or + ~encode.duration.property.types.DefaultDurationProperty or IO[bytes] :return: DefaultDurationProperty. The DefaultDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.DefaultDurationProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -197,12 +199,12 @@ async def iso8601( @overload async def iso8601( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.ISO8601DurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.ISO8601DurationProperty: """iso8601. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.ISO8601DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -228,12 +230,15 @@ async def iso8601( """ async def iso8601( - self, body: Union[_models2.ISO8601DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.ISO8601DurationProperty, _types_models2.ISO8601DurationProperty, IO[bytes]], + **kwargs: Any ) -> _models2.ISO8601DurationProperty: """iso8601. - :param body: Is one of the following types: ISO8601DurationProperty, JSON, IO[bytes] Required. - :type body: ~encode.duration.property.models.ISO8601DurationProperty or JSON or IO[bytes] + :param body: Is either a ISO8601DurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.ISO8601DurationProperty or + ~encode.duration.property.types.ISO8601DurationProperty or IO[bytes] :return: ISO8601DurationProperty. The ISO8601DurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.ISO8601DurationProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -314,12 +319,16 @@ async def int32_seconds( @overload async def int32_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.Int32SecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.Int32SecondsDurationProperty: """int32_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Int32SecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -347,13 +356,15 @@ async def int32_seconds( """ async def int32_seconds( - self, body: Union[_models2.Int32SecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.Int32SecondsDurationProperty, _types_models2.Int32SecondsDurationProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Int32SecondsDurationProperty: """int32_seconds. - :param body: Is one of the following types: Int32SecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.Int32SecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a Int32SecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.Int32SecondsDurationProperty or + ~encode.duration.property.types.Int32SecondsDurationProperty or IO[bytes] :return: Int32SecondsDurationProperty. The Int32SecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Int32SecondsDurationProperty @@ -435,12 +446,16 @@ async def float_seconds( @overload async def float_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.FloatSecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.FloatSecondsDurationProperty: """float_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatSecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -468,13 +483,15 @@ async def float_seconds( """ async def float_seconds( - self, body: Union[_models2.FloatSecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.FloatSecondsDurationProperty, _types_models2.FloatSecondsDurationProperty, IO[bytes]], + **kwargs: Any ) -> _models2.FloatSecondsDurationProperty: """float_seconds. - :param body: Is one of the following types: FloatSecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.FloatSecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a FloatSecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.FloatSecondsDurationProperty or + ~encode.duration.property.types.FloatSecondsDurationProperty or IO[bytes] :return: FloatSecondsDurationProperty. The FloatSecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatSecondsDurationProperty @@ -556,12 +573,16 @@ async def float64_seconds( @overload async def float64_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.Float64SecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.Float64SecondsDurationProperty: """float64_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Float64SecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -589,14 +610,15 @@ async def float64_seconds( """ async def float64_seconds( - self, body: Union[_models2.Float64SecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models2.Float64SecondsDurationProperty, _types_models2.Float64SecondsDurationProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Float64SecondsDurationProperty: """float64_seconds. - :param body: Is one of the following types: Float64SecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.Float64SecondsDurationProperty or JSON or - IO[bytes] + :param body: Is either a Float64SecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.Float64SecondsDurationProperty or + ~encode.duration.property.types.Float64SecondsDurationProperty or IO[bytes] :return: Float64SecondsDurationProperty. The Float64SecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Float64SecondsDurationProperty @@ -678,12 +700,16 @@ async def int32_milliseconds( @overload async def int32_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.Int32MillisecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.Int32MillisecondsDurationProperty: """int32_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Int32MillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -711,14 +737,17 @@ async def int32_milliseconds( """ async def int32_milliseconds( - self, body: Union[_models2.Int32MillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.Int32MillisecondsDurationProperty, _types_models2.Int32MillisecondsDurationProperty, IO[bytes] + ], + **kwargs: Any ) -> _models2.Int32MillisecondsDurationProperty: """int32_milliseconds. - :param body: Is one of the following types: Int32MillisecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.Int32MillisecondsDurationProperty or JSON or - IO[bytes] + :param body: Is either a Int32MillisecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.Int32MillisecondsDurationProperty or + ~encode.duration.property.types.Int32MillisecondsDurationProperty or IO[bytes] :return: Int32MillisecondsDurationProperty. The Int32MillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Int32MillisecondsDurationProperty @@ -800,12 +829,16 @@ async def float_milliseconds( @overload async def float_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.FloatMillisecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.FloatMillisecondsDurationProperty: """float_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatMillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -833,14 +866,17 @@ async def float_milliseconds( """ async def float_milliseconds( - self, body: Union[_models2.FloatMillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.FloatMillisecondsDurationProperty, _types_models2.FloatMillisecondsDurationProperty, IO[bytes] + ], + **kwargs: Any ) -> _models2.FloatMillisecondsDurationProperty: """float_milliseconds. - :param body: Is one of the following types: FloatMillisecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.FloatMillisecondsDurationProperty or JSON or - IO[bytes] + :param body: Is either a FloatMillisecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.FloatMillisecondsDurationProperty or + ~encode.duration.property.types.FloatMillisecondsDurationProperty or IO[bytes] :return: FloatMillisecondsDurationProperty. The FloatMillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatMillisecondsDurationProperty @@ -926,12 +962,16 @@ async def float64_milliseconds( @overload async def float64_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.Float64MillisecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.Float64MillisecondsDurationProperty: """float64_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Float64MillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -959,14 +999,18 @@ async def float64_milliseconds( """ async def float64_milliseconds( - self, body: Union[_models2.Float64MillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.Float64MillisecondsDurationProperty, _types_models2.Float64MillisecondsDurationProperty, IO[bytes] + ], + **kwargs: Any ) -> _models2.Float64MillisecondsDurationProperty: """float64_milliseconds. - :param body: Is one of the following types: Float64MillisecondsDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.property.models.Float64MillisecondsDurationProperty or JSON or - IO[bytes] + :param body: Is either a Float64MillisecondsDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.property.models.Float64MillisecondsDurationProperty or + ~encode.duration.property.types.Float64MillisecondsDurationProperty or IO[bytes] :return: Float64MillisecondsDurationProperty. The Float64MillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Float64MillisecondsDurationProperty @@ -1048,12 +1092,16 @@ async def float_seconds_array( @overload async def float_seconds_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.FloatSecondsDurationArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.FloatSecondsDurationArrayProperty: """float_seconds_array. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatSecondsDurationArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1081,14 +1129,17 @@ async def float_seconds_array( """ async def float_seconds_array( - self, body: Union[_models2.FloatSecondsDurationArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.FloatSecondsDurationArrayProperty, _types_models2.FloatSecondsDurationArrayProperty, IO[bytes] + ], + **kwargs: Any ) -> _models2.FloatSecondsDurationArrayProperty: """float_seconds_array. - :param body: Is one of the following types: FloatSecondsDurationArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.FloatSecondsDurationArrayProperty or JSON or - IO[bytes] + :param body: Is either a FloatSecondsDurationArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.FloatSecondsDurationArrayProperty or + ~encode.duration.property.types.FloatSecondsDurationArrayProperty or IO[bytes] :return: FloatSecondsDurationArrayProperty. The FloatSecondsDurationArrayProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatSecondsDurationArrayProperty @@ -1174,12 +1225,16 @@ async def float_milliseconds_array( @overload async def float_milliseconds_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.FloatMillisecondsDurationArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.FloatMillisecondsDurationArrayProperty: """float_milliseconds_array. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatMillisecondsDurationArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1207,14 +1262,20 @@ async def float_milliseconds_array( """ async def float_milliseconds_array( - self, body: Union[_models2.FloatMillisecondsDurationArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.FloatMillisecondsDurationArrayProperty, + _types_models2.FloatMillisecondsDurationArrayProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models2.FloatMillisecondsDurationArrayProperty: """float_milliseconds_array. - :param body: Is one of the following types: FloatMillisecondsDurationArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.property.models.FloatMillisecondsDurationArrayProperty or JSON or - IO[bytes] + :param body: Is either a FloatMillisecondsDurationArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.property.models.FloatMillisecondsDurationArrayProperty or + ~encode.duration.property.types.FloatMillisecondsDurationArrayProperty or IO[bytes] :return: FloatMillisecondsDurationArrayProperty. The FloatMillisecondsDurationArrayProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatMillisecondsDurationArrayProperty @@ -1300,12 +1361,16 @@ async def int32_seconds_larger_unit( @overload async def int32_seconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.Int32SecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.Int32SecondsLargerUnitDurationProperty: """int32_seconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Int32SecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1333,14 +1398,20 @@ async def int32_seconds_larger_unit( """ async def int32_seconds_larger_unit( - self, body: Union[_models2.Int32SecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.Int32SecondsLargerUnitDurationProperty, + _types_models2.Int32SecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models2.Int32SecondsLargerUnitDurationProperty: """int32_seconds_larger_unit. - :param body: Is one of the following types: Int32SecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.property.models.Int32SecondsLargerUnitDurationProperty or JSON or - IO[bytes] + :param body: Is either a Int32SecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.property.models.Int32SecondsLargerUnitDurationProperty or + ~encode.duration.property.types.Int32SecondsLargerUnitDurationProperty or IO[bytes] :return: Int32SecondsLargerUnitDurationProperty. The Int32SecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Int32SecondsLargerUnitDurationProperty @@ -1426,12 +1497,16 @@ async def float_seconds_larger_unit( @overload async def float_seconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.FloatSecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.FloatSecondsLargerUnitDurationProperty: """float_seconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatSecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1459,14 +1534,20 @@ async def float_seconds_larger_unit( """ async def float_seconds_larger_unit( - self, body: Union[_models2.FloatSecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.FloatSecondsLargerUnitDurationProperty, + _types_models2.FloatSecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models2.FloatSecondsLargerUnitDurationProperty: """float_seconds_larger_unit. - :param body: Is one of the following types: FloatSecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.property.models.FloatSecondsLargerUnitDurationProperty or JSON or - IO[bytes] + :param body: Is either a FloatSecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.property.models.FloatSecondsLargerUnitDurationProperty or + ~encode.duration.property.types.FloatSecondsLargerUnitDurationProperty or IO[bytes] :return: FloatSecondsLargerUnitDurationProperty. The FloatSecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatSecondsLargerUnitDurationProperty @@ -1552,12 +1633,16 @@ async def int32_milliseconds_larger_unit( @overload async def int32_milliseconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.Int32MillisecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.Int32MillisecondsLargerUnitDurationProperty: """int32_milliseconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Int32MillisecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1585,14 +1670,20 @@ async def int32_milliseconds_larger_unit( """ async def int32_milliseconds_larger_unit( - self, body: Union[_models2.Int32MillisecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.Int32MillisecondsLargerUnitDurationProperty, + _types_models2.Int32MillisecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models2.Int32MillisecondsLargerUnitDurationProperty: """int32_milliseconds_larger_unit. - :param body: Is one of the following types: Int32MillisecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. + :param body: Is either a Int32MillisecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. :type body: ~encode.duration.property.models.Int32MillisecondsLargerUnitDurationProperty or - JSON or IO[bytes] + ~encode.duration.property.types.Int32MillisecondsLargerUnitDurationProperty or IO[bytes] :return: Int32MillisecondsLargerUnitDurationProperty. The Int32MillisecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Int32MillisecondsLargerUnitDurationProperty @@ -1678,12 +1769,16 @@ async def float_milliseconds_larger_unit( @overload async def float_milliseconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models2.FloatMillisecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models2.FloatMillisecondsLargerUnitDurationProperty: """float_milliseconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatMillisecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1711,14 +1806,20 @@ async def float_milliseconds_larger_unit( """ async def float_milliseconds_larger_unit( - self, body: Union[_models2.FloatMillisecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models2.FloatMillisecondsLargerUnitDurationProperty, + _types_models2.FloatMillisecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any ) -> _models2.FloatMillisecondsLargerUnitDurationProperty: """float_milliseconds_larger_unit. - :param body: Is one of the following types: FloatMillisecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. + :param body: Is either a FloatMillisecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. :type body: ~encode.duration.property.models.FloatMillisecondsLargerUnitDurationProperty or - JSON or IO[bytes] + ~encode.duration.property.types.FloatMillisecondsLargerUnitDurationProperty or IO[bytes] :return: FloatMillisecondsLargerUnitDurationProperty. The FloatMillisecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatMillisecondsLargerUnitDurationProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/models/_models.py index 31f2c3aac733..573a65ad422d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/models/_models.py @@ -39,17 +39,19 @@ class Float64MillisecondsDurationProperty(_Model): """Float64MillisecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -67,17 +69,19 @@ class Float64SecondsDurationProperty(_Model): """Float64SecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -95,17 +99,19 @@ class FloatMillisecondsDurationArrayProperty(_Model): """FloatMillisecondsDurationArrayProperty. :ivar value: Required. - :vartype value: list[float] + :vartype value: list[~datetime.timedelta] """ - value: list[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: list[datetime.timedelta] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-float" + ) """Required.""" @overload def __init__( self, *, - value: list[float], + value: list[datetime.timedelta], ) -> None: ... @overload @@ -123,17 +129,19 @@ class FloatMillisecondsDurationProperty(_Model): """FloatMillisecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -151,17 +159,19 @@ class FloatMillisecondsLargerUnitDurationProperty(_Model): # pylint: disable=na """FloatMillisecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -179,17 +189,19 @@ class FloatSecondsDurationArrayProperty(_Model): """FloatSecondsDurationArrayProperty. :ivar value: Required. - :vartype value: list[float] + :vartype value: list[~datetime.timedelta] """ - value: list[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: list[datetime.timedelta] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-float" + ) """Required.""" @overload def __init__( self, *, - value: list[float], + value: list[datetime.timedelta], ) -> None: ... @overload @@ -207,17 +219,19 @@ class FloatSecondsDurationProperty(_Model): """FloatSecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -235,17 +249,19 @@ class FloatSecondsLargerUnitDurationProperty(_Model): """FloatSecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: ~datetime.timedelta """ - value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-float" + ) """Required.""" @overload def __init__( self, *, - value: float, + value: datetime.timedelta, ) -> None: ... @overload @@ -263,17 +279,19 @@ class Int32MillisecondsDurationProperty(_Model): """Int32MillisecondsDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: ~datetime.timedelta """ - value: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-int" + ) """Required.""" @overload def __init__( self, *, - value: int, + value: datetime.timedelta, ) -> None: ... @overload @@ -291,17 +309,19 @@ class Int32MillisecondsLargerUnitDurationProperty(_Model): # pylint: disable=na """Int32MillisecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: ~datetime.timedelta """ - value: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-milliseconds-int" + ) """Required.""" @overload def __init__( self, *, - value: int, + value: datetime.timedelta, ) -> None: ... @overload @@ -319,17 +339,19 @@ class Int32SecondsDurationProperty(_Model): """Int32SecondsDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: ~datetime.timedelta """ - value: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-int" + ) """Required.""" @overload def __init__( self, *, - value: int, + value: datetime.timedelta, ) -> None: ... @overload @@ -347,17 +369,19 @@ class Int32SecondsLargerUnitDurationProperty(_Model): """Int32SecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: ~datetime.timedelta """ - value: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + value: datetime.timedelta = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="duration-seconds-int" + ) """Required.""" @overload def __init__( self, *, - value: int, + value: datetime.timedelta, ) -> None: ... @overload diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/operations/_operations.py index 878c489a2bd9..e63f91555cfe 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/operations/_operations.py @@ -20,12 +20,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from ..._configuration import DurationClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -310,12 +309,12 @@ def default( @overload def default( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models1.DefaultDurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models1.DefaultDurationProperty: """default. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.DefaultDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -341,12 +340,15 @@ def default( """ def default( - self, body: Union[_models1.DefaultDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models1.DefaultDurationProperty, _types_models1.DefaultDurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models1.DefaultDurationProperty: """default. - :param body: Is one of the following types: DefaultDurationProperty, JSON, IO[bytes] Required. - :type body: ~encode.duration.property.models.DefaultDurationProperty or JSON or IO[bytes] + :param body: Is either a DefaultDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.DefaultDurationProperty or + ~encode.duration.property.types.DefaultDurationProperty or IO[bytes] :return: DefaultDurationProperty. The DefaultDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.DefaultDurationProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -426,12 +428,12 @@ def iso8601( @overload def iso8601( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models1.ISO8601DurationProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models1.ISO8601DurationProperty: """iso8601. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.ISO8601DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -457,12 +459,15 @@ def iso8601( """ def iso8601( - self, body: Union[_models1.ISO8601DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models1.ISO8601DurationProperty, _types_models1.ISO8601DurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models1.ISO8601DurationProperty: """iso8601. - :param body: Is one of the following types: ISO8601DurationProperty, JSON, IO[bytes] Required. - :type body: ~encode.duration.property.models.ISO8601DurationProperty or JSON or IO[bytes] + :param body: Is either a ISO8601DurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.ISO8601DurationProperty or + ~encode.duration.property.types.ISO8601DurationProperty or IO[bytes] :return: ISO8601DurationProperty. The ISO8601DurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.ISO8601DurationProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -543,12 +548,16 @@ def int32_seconds( @overload def int32_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.Int32SecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.Int32SecondsDurationProperty: """int32_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Int32SecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -576,13 +585,15 @@ def int32_seconds( """ def int32_seconds( - self, body: Union[_models1.Int32SecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models1.Int32SecondsDurationProperty, _types_models1.Int32SecondsDurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models1.Int32SecondsDurationProperty: """int32_seconds. - :param body: Is one of the following types: Int32SecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.Int32SecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a Int32SecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.Int32SecondsDurationProperty or + ~encode.duration.property.types.Int32SecondsDurationProperty or IO[bytes] :return: Int32SecondsDurationProperty. The Int32SecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Int32SecondsDurationProperty @@ -664,12 +675,16 @@ def float_seconds( @overload def float_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.FloatSecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.FloatSecondsDurationProperty: """float_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatSecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -697,13 +712,15 @@ def float_seconds( """ def float_seconds( - self, body: Union[_models1.FloatSecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models1.FloatSecondsDurationProperty, _types_models1.FloatSecondsDurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models1.FloatSecondsDurationProperty: """float_seconds. - :param body: Is one of the following types: FloatSecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.FloatSecondsDurationProperty or JSON or IO[bytes] + :param body: Is either a FloatSecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.FloatSecondsDurationProperty or + ~encode.duration.property.types.FloatSecondsDurationProperty or IO[bytes] :return: FloatSecondsDurationProperty. The FloatSecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatSecondsDurationProperty @@ -785,12 +802,16 @@ def float64_seconds( @overload def float64_seconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.Float64SecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.Float64SecondsDurationProperty: """float64_seconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Float64SecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -818,14 +839,15 @@ def float64_seconds( """ def float64_seconds( - self, body: Union[_models1.Float64SecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models1.Float64SecondsDurationProperty, _types_models1.Float64SecondsDurationProperty, IO[bytes]], + **kwargs: Any, ) -> _models1.Float64SecondsDurationProperty: """float64_seconds. - :param body: Is one of the following types: Float64SecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.Float64SecondsDurationProperty or JSON or - IO[bytes] + :param body: Is either a Float64SecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.Float64SecondsDurationProperty or + ~encode.duration.property.types.Float64SecondsDurationProperty or IO[bytes] :return: Float64SecondsDurationProperty. The Float64SecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Float64SecondsDurationProperty @@ -907,12 +929,16 @@ def int32_milliseconds( @overload def int32_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.Int32MillisecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.Int32MillisecondsDurationProperty: """int32_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Int32MillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -940,14 +966,17 @@ def int32_milliseconds( """ def int32_milliseconds( - self, body: Union[_models1.Int32MillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models1.Int32MillisecondsDurationProperty, _types_models1.Int32MillisecondsDurationProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models1.Int32MillisecondsDurationProperty: """int32_milliseconds. - :param body: Is one of the following types: Int32MillisecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.Int32MillisecondsDurationProperty or JSON or - IO[bytes] + :param body: Is either a Int32MillisecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.Int32MillisecondsDurationProperty or + ~encode.duration.property.types.Int32MillisecondsDurationProperty or IO[bytes] :return: Int32MillisecondsDurationProperty. The Int32MillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Int32MillisecondsDurationProperty @@ -1029,12 +1058,16 @@ def float_milliseconds( @overload def float_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.FloatMillisecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.FloatMillisecondsDurationProperty: """float_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatMillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1062,14 +1095,17 @@ def float_milliseconds( """ def float_milliseconds( - self, body: Union[_models1.FloatMillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models1.FloatMillisecondsDurationProperty, _types_models1.FloatMillisecondsDurationProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models1.FloatMillisecondsDurationProperty: """float_milliseconds. - :param body: Is one of the following types: FloatMillisecondsDurationProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.FloatMillisecondsDurationProperty or JSON or - IO[bytes] + :param body: Is either a FloatMillisecondsDurationProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.FloatMillisecondsDurationProperty or + ~encode.duration.property.types.FloatMillisecondsDurationProperty or IO[bytes] :return: FloatMillisecondsDurationProperty. The FloatMillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatMillisecondsDurationProperty @@ -1155,12 +1191,16 @@ def float64_milliseconds( @overload def float64_milliseconds( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.Float64MillisecondsDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.Float64MillisecondsDurationProperty: """float64_milliseconds. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Float64MillisecondsDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1188,14 +1228,18 @@ def float64_milliseconds( """ def float64_milliseconds( - self, body: Union[_models1.Float64MillisecondsDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models1.Float64MillisecondsDurationProperty, _types_models1.Float64MillisecondsDurationProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models1.Float64MillisecondsDurationProperty: """float64_milliseconds. - :param body: Is one of the following types: Float64MillisecondsDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.property.models.Float64MillisecondsDurationProperty or JSON or - IO[bytes] + :param body: Is either a Float64MillisecondsDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.property.models.Float64MillisecondsDurationProperty or + ~encode.duration.property.types.Float64MillisecondsDurationProperty or IO[bytes] :return: Float64MillisecondsDurationProperty. The Float64MillisecondsDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Float64MillisecondsDurationProperty @@ -1277,12 +1321,16 @@ def float_seconds_array( @overload def float_seconds_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.FloatSecondsDurationArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.FloatSecondsDurationArrayProperty: """float_seconds_array. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatSecondsDurationArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1310,14 +1358,17 @@ def float_seconds_array( """ def float_seconds_array( - self, body: Union[_models1.FloatSecondsDurationArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models1.FloatSecondsDurationArrayProperty, _types_models1.FloatSecondsDurationArrayProperty, IO[bytes] + ], + **kwargs: Any, ) -> _models1.FloatSecondsDurationArrayProperty: """float_seconds_array. - :param body: Is one of the following types: FloatSecondsDurationArrayProperty, JSON, IO[bytes] - Required. - :type body: ~encode.duration.property.models.FloatSecondsDurationArrayProperty or JSON or - IO[bytes] + :param body: Is either a FloatSecondsDurationArrayProperty type or a IO[bytes] type. Required. + :type body: ~encode.duration.property.models.FloatSecondsDurationArrayProperty or + ~encode.duration.property.types.FloatSecondsDurationArrayProperty or IO[bytes] :return: FloatSecondsDurationArrayProperty. The FloatSecondsDurationArrayProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatSecondsDurationArrayProperty @@ -1403,12 +1454,16 @@ def float_milliseconds_array( @overload def float_milliseconds_array( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.FloatMillisecondsDurationArrayProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.FloatMillisecondsDurationArrayProperty: """float_milliseconds_array. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatMillisecondsDurationArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1436,14 +1491,20 @@ def float_milliseconds_array( """ def float_milliseconds_array( - self, body: Union[_models1.FloatMillisecondsDurationArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models1.FloatMillisecondsDurationArrayProperty, + _types_models1.FloatMillisecondsDurationArrayProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models1.FloatMillisecondsDurationArrayProperty: """float_milliseconds_array. - :param body: Is one of the following types: FloatMillisecondsDurationArrayProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.property.models.FloatMillisecondsDurationArrayProperty or JSON or - IO[bytes] + :param body: Is either a FloatMillisecondsDurationArrayProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.property.models.FloatMillisecondsDurationArrayProperty or + ~encode.duration.property.types.FloatMillisecondsDurationArrayProperty or IO[bytes] :return: FloatMillisecondsDurationArrayProperty. The FloatMillisecondsDurationArrayProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatMillisecondsDurationArrayProperty @@ -1529,12 +1590,16 @@ def int32_seconds_larger_unit( @overload def int32_seconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.Int32SecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.Int32SecondsLargerUnitDurationProperty: """int32_seconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Int32SecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1562,14 +1627,20 @@ def int32_seconds_larger_unit( """ def int32_seconds_larger_unit( - self, body: Union[_models1.Int32SecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models1.Int32SecondsLargerUnitDurationProperty, + _types_models1.Int32SecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models1.Int32SecondsLargerUnitDurationProperty: """int32_seconds_larger_unit. - :param body: Is one of the following types: Int32SecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.property.models.Int32SecondsLargerUnitDurationProperty or JSON or - IO[bytes] + :param body: Is either a Int32SecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.property.models.Int32SecondsLargerUnitDurationProperty or + ~encode.duration.property.types.Int32SecondsLargerUnitDurationProperty or IO[bytes] :return: Int32SecondsLargerUnitDurationProperty. The Int32SecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Int32SecondsLargerUnitDurationProperty @@ -1655,12 +1726,16 @@ def float_seconds_larger_unit( @overload def float_seconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.FloatSecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.FloatSecondsLargerUnitDurationProperty: """float_seconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatSecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1688,14 +1763,20 @@ def float_seconds_larger_unit( """ def float_seconds_larger_unit( - self, body: Union[_models1.FloatSecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models1.FloatSecondsLargerUnitDurationProperty, + _types_models1.FloatSecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models1.FloatSecondsLargerUnitDurationProperty: """float_seconds_larger_unit. - :param body: Is one of the following types: FloatSecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. - :type body: ~encode.duration.property.models.FloatSecondsLargerUnitDurationProperty or JSON or - IO[bytes] + :param body: Is either a FloatSecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. + :type body: ~encode.duration.property.models.FloatSecondsLargerUnitDurationProperty or + ~encode.duration.property.types.FloatSecondsLargerUnitDurationProperty or IO[bytes] :return: FloatSecondsLargerUnitDurationProperty. The FloatSecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatSecondsLargerUnitDurationProperty @@ -1781,12 +1862,16 @@ def int32_milliseconds_larger_unit( @overload def int32_milliseconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.Int32MillisecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.Int32MillisecondsLargerUnitDurationProperty: """int32_milliseconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.Int32MillisecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1814,14 +1899,20 @@ def int32_milliseconds_larger_unit( """ def int32_milliseconds_larger_unit( - self, body: Union[_models1.Int32MillisecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models1.Int32MillisecondsLargerUnitDurationProperty, + _types_models1.Int32MillisecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models1.Int32MillisecondsLargerUnitDurationProperty: """int32_milliseconds_larger_unit. - :param body: Is one of the following types: Int32MillisecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. + :param body: Is either a Int32MillisecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. :type body: ~encode.duration.property.models.Int32MillisecondsLargerUnitDurationProperty or - JSON or IO[bytes] + ~encode.duration.property.types.Int32MillisecondsLargerUnitDurationProperty or IO[bytes] :return: Int32MillisecondsLargerUnitDurationProperty. The Int32MillisecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.Int32MillisecondsLargerUnitDurationProperty @@ -1907,12 +1998,16 @@ def float_milliseconds_larger_unit( @overload def float_milliseconds_larger_unit( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, + body: _types_models1.FloatMillisecondsLargerUnitDurationProperty, + *, + content_type: str = "application/json", + **kwargs: Any, ) -> _models1.FloatMillisecondsLargerUnitDurationProperty: """float_milliseconds_larger_unit. :param body: Required. - :type body: JSON + :type body: ~encode.duration.property.types.FloatMillisecondsLargerUnitDurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1940,14 +2035,20 @@ def float_milliseconds_larger_unit( """ def float_milliseconds_larger_unit( - self, body: Union[_models1.FloatMillisecondsLargerUnitDurationProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models1.FloatMillisecondsLargerUnitDurationProperty, + _types_models1.FloatMillisecondsLargerUnitDurationProperty, + IO[bytes], + ], + **kwargs: Any, ) -> _models1.FloatMillisecondsLargerUnitDurationProperty: """float_milliseconds_larger_unit. - :param body: Is one of the following types: FloatMillisecondsLargerUnitDurationProperty, JSON, - IO[bytes] Required. + :param body: Is either a FloatMillisecondsLargerUnitDurationProperty type or a IO[bytes] type. + Required. :type body: ~encode.duration.property.models.FloatMillisecondsLargerUnitDurationProperty or - JSON or IO[bytes] + ~encode.duration.property.types.FloatMillisecondsLargerUnitDurationProperty or IO[bytes] :return: FloatMillisecondsLargerUnitDurationProperty. The FloatMillisecondsLargerUnitDurationProperty is compatible with MutableMapping :rtype: ~encode.duration.property.models.FloatMillisecondsLargerUnitDurationProperty diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/types.py index 7b9fe5b386d9..3d0c9cee02e5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/property/types.py @@ -1,6 +1,5 @@ # coding=utf-8 -import datetime from typing_extensions import Required, TypedDict @@ -8,10 +7,10 @@ class DefaultDurationProperty(TypedDict, total=False): """DefaultDurationProperty. :ivar value: Required. - :vartype value: ~datetime.timedelta + :vartype value: str """ - value: Required[datetime.timedelta] + value: Required[str] """Required.""" @@ -19,10 +18,10 @@ class Float64MillisecondsDurationProperty(TypedDict, total=False): """Float64MillisecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -30,10 +29,10 @@ class Float64SecondsDurationProperty(TypedDict, total=False): """Float64SecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -41,10 +40,10 @@ class FloatMillisecondsDurationArrayProperty(TypedDict, total=False): """FloatMillisecondsDurationArrayProperty. :ivar value: Required. - :vartype value: list[float] + :vartype value: list[str] """ - value: Required[list[float]] + value: Required[list[str]] """Required.""" @@ -52,10 +51,10 @@ class FloatMillisecondsDurationProperty(TypedDict, total=False): """FloatMillisecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -63,10 +62,10 @@ class FloatMillisecondsLargerUnitDurationProperty(TypedDict, total=False): # py """FloatMillisecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -74,10 +73,10 @@ class FloatSecondsDurationArrayProperty(TypedDict, total=False): """FloatSecondsDurationArrayProperty. :ivar value: Required. - :vartype value: list[float] + :vartype value: list[str] """ - value: Required[list[float]] + value: Required[list[str]] """Required.""" @@ -85,10 +84,10 @@ class FloatSecondsDurationProperty(TypedDict, total=False): """FloatSecondsDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -96,10 +95,10 @@ class FloatSecondsLargerUnitDurationProperty(TypedDict, total=False): """FloatSecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: float + :vartype value: str """ - value: Required[float] + value: Required[str] """Required.""" @@ -107,10 +106,10 @@ class Int32MillisecondsDurationProperty(TypedDict, total=False): """Int32MillisecondsDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: str """ - value: Required[int] + value: Required[str] """Required.""" @@ -118,10 +117,10 @@ class Int32MillisecondsLargerUnitDurationProperty(TypedDict, total=False): # py """Int32MillisecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: str """ - value: Required[int] + value: Required[str] """Required.""" @@ -129,10 +128,10 @@ class Int32SecondsDurationProperty(TypedDict, total=False): """Int32SecondsDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: str """ - value: Required[int] + value: Required[str] """Required.""" @@ -140,10 +139,10 @@ class Int32SecondsLargerUnitDurationProperty(TypedDict, total=False): """Int32SecondsLargerUnitDurationProperty. :ivar value: Required. - :vartype value: int + :vartype value: str """ - value: Required[int] + value: Required[str] """Required.""" @@ -151,8 +150,8 @@ class ISO8601DurationProperty(TypedDict, total=False): """ISO8601DurationProperty. :ivar value: Required. - :vartype value: ~datetime.timedelta + :vartype value: str """ - value: Required[datetime.timedelta] + value: Required[str] """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/aio/operations/_operations.py index 9e7441f9c215..19da344dde16 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/aio/operations/_operations.py @@ -143,11 +143,11 @@ async def iso8601(self, *, input: datetime.timedelta, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_seconds(self, *, input: int, **kwargs: Any) -> None: + async def int32_seconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """int32_seconds. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -187,11 +187,11 @@ async def int32_seconds(self, *, input: int, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_seconds_larger_unit(self, *, input: int, **kwargs: Any) -> None: + async def int32_seconds_larger_unit(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """int32_seconds_larger_unit. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -231,11 +231,11 @@ async def int32_seconds_larger_unit(self, *, input: int, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float_seconds(self, *, input: float, **kwargs: Any) -> None: + async def float_seconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float_seconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -275,11 +275,11 @@ async def float_seconds(self, *, input: float, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float_seconds_larger_unit(self, *, input: float, **kwargs: Any) -> None: + async def float_seconds_larger_unit(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float_seconds_larger_unit. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -319,11 +319,11 @@ async def float_seconds_larger_unit(self, *, input: float, **kwargs: Any) -> Non if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float64_seconds(self, *, input: float, **kwargs: Any) -> None: + async def float64_seconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float64_seconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -363,11 +363,11 @@ async def float64_seconds(self, *, input: float, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_milliseconds(self, *, input: int, **kwargs: Any) -> None: + async def int32_milliseconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """int32_milliseconds. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -407,11 +407,11 @@ async def int32_milliseconds(self, *, input: int, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_milliseconds_larger_unit(self, *, input: int, **kwargs: Any) -> None: + async def int32_milliseconds_larger_unit(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """int32_milliseconds_larger_unit. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -451,11 +451,11 @@ async def int32_milliseconds_larger_unit(self, *, input: int, **kwargs: Any) -> if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float_milliseconds(self, *, input: float, **kwargs: Any) -> None: + async def float_milliseconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float_milliseconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -495,11 +495,11 @@ async def float_milliseconds(self, *, input: float, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float_milliseconds_larger_unit(self, *, input: float, **kwargs: Any) -> None: + async def float_milliseconds_larger_unit(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float_milliseconds_larger_unit. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -539,11 +539,11 @@ async def float_milliseconds_larger_unit(self, *, input: float, **kwargs: Any) - if cls: return cls(pipeline_response, None, {}) # type: ignore - async def float64_milliseconds(self, *, input: float, **kwargs: Any) -> None: + async def float64_milliseconds(self, *, input: datetime.timedelta, **kwargs: Any) -> None: """float64_milliseconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -583,11 +583,11 @@ async def float64_milliseconds(self, *, input: float, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_seconds_array(self, *, input: list[int], **kwargs: Any) -> None: + async def int32_seconds_array(self, *, input: list[datetime.timedelta], **kwargs: Any) -> None: """int32_seconds_array. :keyword input: Required. - :paramtype input: list[int] + :paramtype input: list[~datetime.timedelta] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -627,11 +627,11 @@ async def int32_seconds_array(self, *, input: list[int], **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - async def int32_milliseconds_array(self, *, input: list[int], **kwargs: Any) -> None: + async def int32_milliseconds_array(self, *, input: list[datetime.timedelta], **kwargs: Any) -> None: """int32_milliseconds_array. :keyword input: Required. - :paramtype input: list[int] + :paramtype input: list[~datetime.timedelta] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/operations/_operations.py index 2167ca34a17f..fae63f4cbb7a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/operations/_operations.py @@ -50,20 +50,20 @@ def build_query_iso8601_request(*, input: datetime.timedelta, **kwargs: Any) -> return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_int32_seconds_request(*, input: int, **kwargs: Any) -> HttpRequest: +def build_query_int32_seconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/int32-seconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "int") + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-int") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_query_int32_seconds_larger_unit_request( # pylint: disable=name-too-long - *, input: int, **kwargs: Any + *, input: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -71,25 +71,25 @@ def build_query_int32_seconds_larger_unit_request( # pylint: disable=name-too-l _url = "/encode/duration/query/int32-seconds-larger-unit" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "int") + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-int") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_float_seconds_request(*, input: float, **kwargs: Any) -> HttpRequest: +def build_query_float_seconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/float-seconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_query_float_seconds_larger_unit_request( # pylint: disable=name-too-long - *, input: float, **kwargs: Any + *, input: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -97,37 +97,37 @@ def build_query_float_seconds_larger_unit_request( # pylint: disable=name-too-l _url = "/encode/duration/query/float-seconds-larger-unit" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_float64_seconds_request(*, input: float, **kwargs: Any) -> HttpRequest: +def build_query_float64_seconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/float64-seconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-seconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_int32_milliseconds_request(*, input: int, **kwargs: Any) -> HttpRequest: +def build_query_int32_milliseconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/int32-milliseconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "int") + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-int") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_query_int32_milliseconds_larger_unit_request( # pylint: disable=name-too-long - *, input: int, **kwargs: Any + *, input: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -135,25 +135,25 @@ def build_query_int32_milliseconds_larger_unit_request( # pylint: disable=name- _url = "/encode/duration/query/int32-milliseconds-larger-unit" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "int") + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-int") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_float_milliseconds_request(*, input: float, **kwargs: Any) -> HttpRequest: +def build_query_float_milliseconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/float-milliseconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_query_float_milliseconds_larger_unit_request( # pylint: disable=name-too-long - *, input: float, **kwargs: Any + *, input: datetime.timedelta, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -161,37 +161,37 @@ def build_query_float_milliseconds_larger_unit_request( # pylint: disable=name- _url = "/encode/duration/query/float-milliseconds-larger-unit" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_float64_milliseconds_request(*, input: float, **kwargs: Any) -> HttpRequest: +def build_query_float64_milliseconds_request(*, input: datetime.timedelta, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/float64-milliseconds" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "float") + _params["input"] = _SERIALIZER.query("input", input, "duration-milliseconds-float") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) -def build_query_int32_seconds_array_request(*, input: list[int], **kwargs: Any) -> HttpRequest: +def build_query_int32_seconds_array_request(*, input: list[datetime.timedelta], **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) # Construct URL _url = "/encode/duration/query/int32-seconds-array" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "[int]", div=",") + _params["input"] = _SERIALIZER.query("input", input, "[duration-seconds-int]", div=",") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) def build_query_int32_milliseconds_array_request( # pylint: disable=name-too-long - *, input: list[int], **kwargs: Any + *, input: list[datetime.timedelta], **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -199,7 +199,7 @@ def build_query_int32_milliseconds_array_request( # pylint: disable=name-too-lo _url = "/encode/duration/query/int32-milliseconds-array" # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "[int]", div=",") + _params["input"] = _SERIALIZER.query("input", input, "[duration-milliseconds-int]", div=",") return HttpRequest(method="GET", url=_url, params=_params, **kwargs) @@ -313,11 +313,13 @@ def iso8601( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) # type: ignore - def int32_seconds(self, *, input: int, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + def int32_seconds( # pylint: disable=inconsistent-return-statements + self, *, input: datetime.timedelta, **kwargs: Any + ) -> None: """int32_seconds. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -358,12 +360,12 @@ def int32_seconds(self, *, input: int, **kwargs: Any) -> None: # pylint: disabl return cls(pipeline_response, None, {}) # type: ignore def int32_seconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, input: int, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """int32_seconds_larger_unit. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -403,11 +405,13 @@ def int32_seconds_larger_unit( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) # type: ignore - def float_seconds(self, *, input: float, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + def float_seconds( # pylint: disable=inconsistent-return-statements + self, *, input: datetime.timedelta, **kwargs: Any + ) -> None: """float_seconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -448,12 +452,12 @@ def float_seconds(self, *, input: float, **kwargs: Any) -> None: # pylint: disa return cls(pipeline_response, None, {}) # type: ignore def float_seconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, input: float, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """float_seconds_larger_unit. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -493,11 +497,13 @@ def float_seconds_larger_unit( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) # type: ignore - def float64_seconds(self, *, input: float, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + def float64_seconds( # pylint: disable=inconsistent-return-statements + self, *, input: datetime.timedelta, **kwargs: Any + ) -> None: """float64_seconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -538,12 +544,12 @@ def float64_seconds(self, *, input: float, **kwargs: Any) -> None: # pylint: di return cls(pipeline_response, None, {}) # type: ignore def int32_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, input: int, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """int32_milliseconds. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -584,12 +590,12 @@ def int32_milliseconds( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def int32_milliseconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, input: int, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """int32_milliseconds_larger_unit. :keyword input: Required. - :paramtype input: int + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -630,12 +636,12 @@ def int32_milliseconds_larger_unit( # pylint: disable=inconsistent-return-state return cls(pipeline_response, None, {}) # type: ignore def float_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, input: float, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """float_milliseconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -676,12 +682,12 @@ def float_milliseconds( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def float_milliseconds_larger_unit( # pylint: disable=inconsistent-return-statements - self, *, input: float, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """float_milliseconds_larger_unit. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -722,12 +728,12 @@ def float_milliseconds_larger_unit( # pylint: disable=inconsistent-return-state return cls(pipeline_response, None, {}) # type: ignore def float64_milliseconds( # pylint: disable=inconsistent-return-statements - self, *, input: float, **kwargs: Any + self, *, input: datetime.timedelta, **kwargs: Any ) -> None: """float64_milliseconds. :keyword input: Required. - :paramtype input: float + :paramtype input: ~datetime.timedelta :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -768,12 +774,12 @@ def float64_milliseconds( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def int32_seconds_array( # pylint: disable=inconsistent-return-statements - self, *, input: list[int], **kwargs: Any + self, *, input: list[datetime.timedelta], **kwargs: Any ) -> None: """int32_seconds_array. :keyword input: Required. - :paramtype input: list[int] + :paramtype input: list[~datetime.timedelta] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -814,12 +820,12 @@ def int32_seconds_array( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore def int32_milliseconds_array( # pylint: disable=inconsistent-return-statements - self, *, input: list[int], **kwargs: Any + self, *, input: list[datetime.timedelta], **kwargs: Any ) -> None: """int32_milliseconds_array. :keyword input: Required. - :paramtype input: list[int] + :paramtype input: list[~datetime.timedelta] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/encode/duration/query/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/pyproject.toml index 80959aaf243b..40f9de7da6ac 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-duration/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/aio/operations/_operations.py index b3d5d99e915c..f5f239ffbef3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/aio/operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import NumericClientConfiguration @@ -29,7 +29,6 @@ build_property_uint8_as_string_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -69,12 +68,12 @@ async def safeint_as_string( @overload async def safeint_as_string( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types_models2.SafeintAsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.SafeintAsStringProperty: """safeint_as_string. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.property.types.SafeintAsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -100,12 +99,15 @@ async def safeint_as_string( """ async def safeint_as_string( - self, value: Union[_models2.SafeintAsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, + value: Union[_models2.SafeintAsStringProperty, _types_models2.SafeintAsStringProperty, IO[bytes]], + **kwargs: Any ) -> _models2.SafeintAsStringProperty: """safeint_as_string. - :param value: Is one of the following types: SafeintAsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.property.models.SafeintAsStringProperty or JSON or IO[bytes] + :param value: Is either a SafeintAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.property.models.SafeintAsStringProperty or + ~encode.numeric.property.types.SafeintAsStringProperty or IO[bytes] :return: SafeintAsStringProperty. The SafeintAsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.property.models.SafeintAsStringProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -185,12 +187,12 @@ async def uint32_as_string_optional( @overload async def uint32_as_string_optional( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types_models2.Uint32AsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Uint32AsStringProperty: """uint32_as_string_optional. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.property.types.Uint32AsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -216,12 +218,15 @@ async def uint32_as_string_optional( """ async def uint32_as_string_optional( - self, value: Union[_models2.Uint32AsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, + value: Union[_models2.Uint32AsStringProperty, _types_models2.Uint32AsStringProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Uint32AsStringProperty: """uint32_as_string_optional. - :param value: Is one of the following types: Uint32AsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.property.models.Uint32AsStringProperty or JSON or IO[bytes] + :param value: Is either a Uint32AsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.property.models.Uint32AsStringProperty or + ~encode.numeric.property.types.Uint32AsStringProperty or IO[bytes] :return: Uint32AsStringProperty. The Uint32AsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.property.models.Uint32AsStringProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -301,12 +306,12 @@ async def uint8_as_string( @overload async def uint8_as_string( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types_models2.Uint8AsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models2.Uint8AsStringProperty: """uint8_as_string. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.property.types.Uint8AsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -332,12 +337,15 @@ async def uint8_as_string( """ async def uint8_as_string( - self, value: Union[_models2.Uint8AsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, + value: Union[_models2.Uint8AsStringProperty, _types_models2.Uint8AsStringProperty, IO[bytes]], + **kwargs: Any ) -> _models2.Uint8AsStringProperty: """uint8_as_string. - :param value: Is one of the following types: Uint8AsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.property.models.Uint8AsStringProperty or JSON or IO[bytes] + :param value: Is either a Uint8AsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.property.models.Uint8AsStringProperty or + ~encode.numeric.property.types.Uint8AsStringProperty or IO[bytes] :return: Uint8AsStringProperty. The Uint8AsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.property.models.Uint8AsStringProperty :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/operations/_operations.py index 3fce12102f87..9e3ffa064b73 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/operations/_operations.py @@ -19,12 +19,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from ..._configuration import NumericClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -118,12 +117,12 @@ def safeint_as_string( @overload def safeint_as_string( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types_models1.SafeintAsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models1.SafeintAsStringProperty: """safeint_as_string. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.property.types.SafeintAsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -149,12 +148,15 @@ def safeint_as_string( """ def safeint_as_string( - self, value: Union[_models1.SafeintAsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, + value: Union[_models1.SafeintAsStringProperty, _types_models1.SafeintAsStringProperty, IO[bytes]], + **kwargs: Any ) -> _models1.SafeintAsStringProperty: """safeint_as_string. - :param value: Is one of the following types: SafeintAsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.property.models.SafeintAsStringProperty or JSON or IO[bytes] + :param value: Is either a SafeintAsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.property.models.SafeintAsStringProperty or + ~encode.numeric.property.types.SafeintAsStringProperty or IO[bytes] :return: SafeintAsStringProperty. The SafeintAsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.property.models.SafeintAsStringProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -234,12 +236,12 @@ def uint32_as_string_optional( @overload def uint32_as_string_optional( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types_models1.Uint32AsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models1.Uint32AsStringProperty: """uint32_as_string_optional. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.property.types.Uint32AsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -265,12 +267,15 @@ def uint32_as_string_optional( """ def uint32_as_string_optional( - self, value: Union[_models1.Uint32AsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, + value: Union[_models1.Uint32AsStringProperty, _types_models1.Uint32AsStringProperty, IO[bytes]], + **kwargs: Any ) -> _models1.Uint32AsStringProperty: """uint32_as_string_optional. - :param value: Is one of the following types: Uint32AsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.property.models.Uint32AsStringProperty or JSON or IO[bytes] + :param value: Is either a Uint32AsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.property.models.Uint32AsStringProperty or + ~encode.numeric.property.types.Uint32AsStringProperty or IO[bytes] :return: Uint32AsStringProperty. The Uint32AsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.property.models.Uint32AsStringProperty :raises ~corehttp.exceptions.HttpResponseError: @@ -350,12 +355,12 @@ def uint8_as_string( @overload def uint8_as_string( - self, value: JSON, *, content_type: str = "application/json", **kwargs: Any + self, value: _types_models1.Uint8AsStringProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models1.Uint8AsStringProperty: """uint8_as_string. :param value: Required. - :type value: JSON + :type value: ~encode.numeric.property.types.Uint8AsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -381,12 +386,15 @@ def uint8_as_string( """ def uint8_as_string( - self, value: Union[_models1.Uint8AsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, + value: Union[_models1.Uint8AsStringProperty, _types_models1.Uint8AsStringProperty, IO[bytes]], + **kwargs: Any ) -> _models1.Uint8AsStringProperty: """uint8_as_string. - :param value: Is one of the following types: Uint8AsStringProperty, JSON, IO[bytes] Required. - :type value: ~encode.numeric.property.models.Uint8AsStringProperty or JSON or IO[bytes] + :param value: Is either a Uint8AsStringProperty type or a IO[bytes] type. Required. + :type value: ~encode.numeric.property.models.Uint8AsStringProperty or + ~encode.numeric.property.types.Uint8AsStringProperty or IO[bytes] :return: Uint8AsStringProperty. The Uint8AsStringProperty is compatible with MutableMapping :rtype: ~encode.numeric.property.models.Uint8AsStringProperty :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/encode/numeric/property/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/pyproject.toml index 39fc7b735ca3..4037af17e682 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/encode-numeric/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_operations/_operations.py index f03445fdf876..63e5d1511201 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import RecursiveClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -80,11 +79,11 @@ def put(self, input: _models.Extension, *, content_type: str = "application/json """ @overload - def put(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, input: _types.Extension, *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param input: Required. - :type input: JSON + :type input: ~generation.subdir._generated.types.Extension :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -108,12 +107,13 @@ def put(self, input: IO[bytes], *, content_type: str = "application/json", **kwa """ def put( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Extension, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Extension, _types.Extension, IO[bytes]], **kwargs: Any ) -> None: """put. - :param input: Is one of the following types: Extension, JSON, IO[bytes] Required. - :type input: ~generation.subdir._generated.models.Extension or JSON or IO[bytes] + :param input: Is either a Extension type or a IO[bytes] type. Required. + :type input: ~generation.subdir._generated.models.Extension or + ~generation.subdir._generated.types.Extension or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/aio/_operations/_operations.py index a63b5be9a905..73b23446a3c2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/aio/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_recursive_get_request, build_recursive_put_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import RecursiveClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -49,11 +48,11 @@ async def put(self, input: _models.Extension, *, content_type: str = "applicatio """ @overload - async def put(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, input: _types.Extension, *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param input: Required. - :type input: JSON + :type input: ~generation.subdir._generated.types.Extension :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -76,11 +75,12 @@ async def put(self, input: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, input: Union[_models.Extension, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, input: Union[_models.Extension, _types.Extension, IO[bytes]], **kwargs: Any) -> None: """put. - :param input: Is one of the following types: Extension, JSON, IO[bytes] Required. - :type input: ~generation.subdir._generated.models.Extension or JSON or IO[bytes] + :param input: Is either a Extension type or a IO[bytes] type. Required. + :type input: ~generation.subdir._generated.models.Extension or + ~generation.subdir._generated.types.Extension or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/types.py new file mode 100644 index 000000000000..031fe0891b38 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/generation/subdir/_generated/types.py @@ -0,0 +1,26 @@ +# coding=utf-8 + +from typing_extensions import Required, TypedDict + + +class Element(TypedDict, total=False): + """element. + + :ivar extension: + :vartype extension: list["Extension"] + """ + + extension: list["Extension"] + + +class Extension(Element): + """extension. + + :ivar extension: + :vartype extension: list["Extension"] + :ivar level: Required. + :vartype level: int + """ + + level: Required[int] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/pyproject.toml index 3a8f74061ffd..252b68ee1ea2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/aio/operations/_operations.py index 3c73cbea6f61..3e80652c6e86 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/aio/operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ..._utils.utils import ClientMixinABC @@ -31,7 +31,6 @@ ) from .._configuration import AddedClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -71,12 +70,12 @@ async def v2_in_interface( @overload async def v2_in_interface( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV2: """v2_in_interface. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -106,11 +105,14 @@ async def v2_in_interface( params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - async def v2_in_interface(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + async def v2_in_interface( + self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV2 or + ~generation.subdir2._generated.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~generation.subdir2._generated.models.ModelV2 :raises ~corehttp.exceptions.HttpResponseError: @@ -198,12 +200,12 @@ async def v1( @overload async def v1( - self, body: JSON, *, header_v2: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV1, *, header_v2: str, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV1: """v1. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV1 :keyword header_v2: Required. :paramtype header_v2: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -237,12 +239,13 @@ async def v1( api_versions_list=["v1", "v2"], ) async def v1( - self, body: Union[_models.ModelV1, JSON, IO[bytes]], *, header_v2: str, **kwargs: Any + self, body: Union[_models.ModelV1, _types.ModelV1, IO[bytes]], *, header_v2: str, **kwargs: Any ) -> _models.ModelV1: """v1. - :param body: Is one of the following types: ModelV1, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV1 or JSON or IO[bytes] + :param body: Is either a ModelV1 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV1 or + ~generation.subdir2._generated.types.ModelV1 or IO[bytes] :keyword header_v2: Required. :paramtype header_v2: str :return: ModelV1. The ModelV1 is compatible with MutableMapping @@ -327,11 +330,13 @@ async def v2( """ @overload - async def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + async def v2( + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -359,11 +364,12 @@ async def v2(self, body: IO[bytes], *, content_type: str = "application/json", * params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - async def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + async def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV2 or + ~generation.subdir2._generated.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~generation.subdir2._generated.models.ModelV2 :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/models/_models.py index c3756af7edd2..171665c080fa 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/models/_models.py @@ -6,7 +6,7 @@ from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - from .. import _types, models as _models + from .. import _unions, models as _models class ModelV1(_Model): @@ -26,7 +26,7 @@ class ModelV1(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Known values are: \"enumMemberV1\" and \"enumMemberV2\".""" - union_prop: "_types.UnionV1" = rest_field( + union_prop: "_unions.UnionV1" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a int type.""" @@ -37,7 +37,7 @@ def __init__( *, prop: str, enum_prop: Union[str, "_models.EnumV1"], - union_prop: "_types.UnionV1", + union_prop: "_unions.UnionV1", ) -> None: ... @overload @@ -68,7 +68,7 @@ class ModelV2(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. \"enumMember\"""" - union_prop: "_types.UnionV2" = rest_field( + union_prop: "_unions.UnionV2" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a int type.""" @@ -79,7 +79,7 @@ def __init__( *, prop: str, enum_prop: Union[str, "_models.EnumV2"], - union_prop: "_types.UnionV2", + union_prop: "_unions.UnionV2", ) -> None: ... @overload diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/operations/_operations.py index bb2138fb06b9..c3bd99441518 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/operations/_operations.py @@ -19,14 +19,13 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import AddedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer from .._utils.utils import ClientMixinABC from .._validation import api_version_validation -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -120,11 +119,13 @@ def v2_in_interface( """ @overload - def v2_in_interface(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + def v2_in_interface( + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -154,11 +155,14 @@ def v2_in_interface( params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - def v2_in_interface(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + def v2_in_interface( + self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV2 or + ~generation.subdir2._generated.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~generation.subdir2._generated.models.ModelV2 :raises ~corehttp.exceptions.HttpResponseError: @@ -244,12 +248,12 @@ def v1( @overload def v1( - self, body: JSON, *, header_v2: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV1, *, header_v2: str, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV1: """v1. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV1 :keyword header_v2: Required. :paramtype header_v2: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -282,11 +286,14 @@ def v1( params_added_on={"v2": ["header_v2"]}, api_versions_list=["v1", "v2"], ) - def v1(self, body: Union[_models.ModelV1, JSON, IO[bytes]], *, header_v2: str, **kwargs: Any) -> _models.ModelV1: + def v1( + self, body: Union[_models.ModelV1, _types.ModelV1, IO[bytes]], *, header_v2: str, **kwargs: Any + ) -> _models.ModelV1: """v1. - :param body: Is one of the following types: ModelV1, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV1 or JSON or IO[bytes] + :param body: Is either a ModelV1 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV1 or + ~generation.subdir2._generated.types.ModelV1 or IO[bytes] :keyword header_v2: Required. :paramtype header_v2: str :return: ModelV1. The ModelV1 is compatible with MutableMapping @@ -367,11 +374,11 @@ def v2(self, body: _models.ModelV2, *, content_type: str = "application/json", * """ @overload - def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + def v2(self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~generation.subdir2._generated.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -399,11 +406,12 @@ def v2(self, body: IO[bytes], *, content_type: str = "application/json", **kwarg params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~generation.subdir2._generated.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~generation.subdir2._generated.models.ModelV2 or + ~generation.subdir2._generated.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~generation.subdir2._generated.models.ModelV2 :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/types.py index 9615a5b2026e..ffb16db35d23 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/generation/subdir2/_generated/types.py @@ -14,9 +14,9 @@ class ModelV1(TypedDict, total=False): :ivar prop: Required. :vartype prop: str :ivar enum_prop: Required. Known values are: "enumMemberV1" and "enumMemberV2". - :vartype enum_prop: str or ~generation.subdir2.models.EnumV1 + :vartype enum_prop: Union[str, "EnumV1"] :ivar union_prop: Required. Is either a str type or a int type. - :vartype union_prop: str or int + :vartype union_prop: "_unions.UnionV1" """ prop: Required[str] @@ -33,9 +33,9 @@ class ModelV2(TypedDict, total=False): :ivar prop: Required. :vartype prop: str :ivar enum_prop: Required. "enumMember" - :vartype enum_prop: str or ~generation.subdir2.models.EnumV2 + :vartype enum_prop: Union[str, "EnumV2"] :ivar union_prop: Required. Is either a str type or a int type. - :vartype union_prop: str or int + :vartype union_prop: "_unions.UnionV2" """ prop: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/pyproject.toml index 487fe99786db..77fdeb8c8cbe 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/generation-subdir2/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_operations/_operations.py index 319ad0ce3dac..0ff43d232617 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import VisibilityClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -169,12 +168,12 @@ def get_model( @overload def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -204,12 +203,17 @@ def get_model( """ def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -294,12 +298,12 @@ def head_model( @overload def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> None: """head_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -329,12 +333,17 @@ def head_model( """ def head_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> None: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: None @@ -403,11 +412,13 @@ def put_model( """ @overload - def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -431,12 +442,13 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", """ def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -502,11 +514,13 @@ def patch_model( """ @overload - def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -530,12 +544,13 @@ def patch_model(self, input: IO[bytes], *, content_type: str = "application/json """ def patch_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -601,11 +616,13 @@ def post_model( """ @overload - def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -629,12 +646,13 @@ def post_model(self, input: IO[bytes], *, content_type: str = "application/json" """ def post_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -700,11 +718,13 @@ def delete_model( """ @overload - def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -728,12 +748,13 @@ def delete_model(self, input: IO[bytes], *, content_type: str = "application/jso """ def delete_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -800,12 +821,12 @@ def put_read_only_model( @overload def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -831,12 +852,13 @@ def put_read_only_model( """ def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.ReadOnlyModel or + ~headasbooleanfalse.types.ReadOnlyModel or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~headasbooleanfalse.models.ReadOnlyModel :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_operations/_operations.py index d3c8f53f4a0e..eabae34a3249 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_visibility_delete_model_request, build_visibility_get_model_request, @@ -33,7 +33,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import VisibilityClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -62,12 +61,12 @@ async def get_model( @overload async def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -97,12 +96,17 @@ async def get_model( """ async def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -189,12 +193,12 @@ async def head_model( @overload async def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> None: """head_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -224,12 +228,17 @@ async def head_model( """ async def head_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> None: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: None @@ -300,11 +309,13 @@ async def put_model( """ @overload - async def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -327,11 +338,14 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -399,11 +413,13 @@ async def patch_model( """ @overload - async def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -426,11 +442,14 @@ async def patch_model(self, input: IO[bytes], *, content_type: str = "applicatio :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -498,11 +517,13 @@ async def post_model( """ @overload - async def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -525,11 +546,14 @@ async def post_model(self, input: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def post_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def post_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -597,11 +621,13 @@ async def delete_model( """ @overload - async def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -624,11 +650,14 @@ async def delete_model(self, input: IO[bytes], *, content_type: str = "applicati :raises ~corehttp.exceptions.HttpResponseError: """ - async def delete_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def delete_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.VisibilityModel or + ~headasbooleanfalse.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -697,12 +726,12 @@ async def put_read_only_model( @overload async def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleanfalse.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -728,12 +757,13 @@ async def put_read_only_model( """ async def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~headasbooleanfalse.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~headasbooleanfalse.models.ReadOnlyModel or + ~headasbooleanfalse.types.ReadOnlyModel or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~headasbooleanfalse.models.ReadOnlyModel :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/headasbooleanfalse/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/pyproject.toml index 4b4aecb5e246..77922a015430 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleanfalse/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_operations/_operations.py index c2e15a01e909..ed4c4bc46728 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import VisibilityClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -169,12 +168,12 @@ def get_model( @overload def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -204,12 +203,17 @@ def get_model( """ def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -294,12 +298,12 @@ def head_model( @overload def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> bool: """head_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -329,12 +333,17 @@ def head_model( """ def head_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> bool: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: bool @@ -404,11 +413,13 @@ def put_model( """ @overload - def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -432,12 +443,13 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", """ def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -503,11 +515,13 @@ def patch_model( """ @overload - def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -531,12 +545,13 @@ def patch_model(self, input: IO[bytes], *, content_type: str = "application/json """ def patch_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -602,11 +617,13 @@ def post_model( """ @overload - def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -630,12 +647,13 @@ def post_model(self, input: IO[bytes], *, content_type: str = "application/json" """ def post_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -701,11 +719,13 @@ def delete_model( """ @overload - def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -729,12 +749,13 @@ def delete_model(self, input: IO[bytes], *, content_type: str = "application/jso """ def delete_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -801,12 +822,12 @@ def put_read_only_model( @overload def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -832,12 +853,13 @@ def put_read_only_model( """ def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.ReadOnlyModel or ~headasbooleantrue.types.ReadOnlyModel + or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~headasbooleantrue.models.ReadOnlyModel :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_operations/_operations.py index 247a46dca1db..91ecfc9fcf33 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_visibility_delete_model_request, build_visibility_get_model_request, @@ -33,7 +33,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import VisibilityClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -62,12 +61,12 @@ async def get_model( @overload async def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -97,12 +96,17 @@ async def get_model( """ async def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -189,12 +193,12 @@ async def head_model( @overload async def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> bool: """head_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -224,12 +228,17 @@ async def head_model( """ async def head_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> bool: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: bool @@ -301,11 +310,13 @@ async def put_model( """ @overload - async def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -328,11 +339,14 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -400,11 +414,13 @@ async def patch_model( """ @overload - async def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -427,11 +443,14 @@ async def patch_model(self, input: IO[bytes], *, content_type: str = "applicatio :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -499,11 +518,13 @@ async def post_model( """ @overload - async def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -526,11 +547,14 @@ async def post_model(self, input: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def post_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def post_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -598,11 +622,13 @@ async def delete_model( """ @overload - async def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -625,11 +651,14 @@ async def delete_model(self, input: IO[bytes], *, content_type: str = "applicati :raises ~corehttp.exceptions.HttpResponseError: """ - async def delete_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def delete_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.VisibilityModel or + ~headasbooleantrue.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -698,12 +727,12 @@ async def put_read_only_model( @overload async def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~headasbooleantrue.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -729,12 +758,13 @@ async def put_read_only_model( """ async def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~headasbooleantrue.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~headasbooleantrue.models.ReadOnlyModel or ~headasbooleantrue.types.ReadOnlyModel + or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~headasbooleantrue.models.ReadOnlyModel :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/headasbooleantrue/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/pyproject.toml index 292f5b43b922..53f5f42183c7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/headasbooleantrue/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/aio/operations/_operations.py index b58f7052c7db..d4da41ed0e03 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/aio/operations/_operations.py @@ -17,13 +17,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ...._utils.model_base import SdkJSONEncoder from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import BasicClientConfiguration from ...operations._operations import build_explicit_body_simple_request -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -60,11 +59,11 @@ async def simple(self, body: _models2.User, *, content_type: str = "application/ """ @overload - async def simple(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def simple(self, body: _types_models2.User, *, content_type: str = "application/json", **kwargs: Any) -> None: """simple. :param body: Required. - :type body: JSON + :type body: ~parameters.basic.explicitbody.types.User :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -87,11 +86,12 @@ async def simple(self, body: IO[bytes], *, content_type: str = "application/json :raises ~corehttp.exceptions.HttpResponseError: """ - async def simple(self, body: Union[_models2.User, JSON, IO[bytes]], **kwargs: Any) -> None: + async def simple(self, body: Union[_models2.User, _types_models2.User, IO[bytes]], **kwargs: Any) -> None: """simple. - :param body: Is one of the following types: User, JSON, IO[bytes] Required. - :type body: ~parameters.basic.explicitbody.models.User or JSON or IO[bytes] + :param body: Is either a User type or a IO[bytes] type. Required. + :type body: ~parameters.basic.explicitbody.models.User or + ~parameters.basic.explicitbody.types.User or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/operations/_operations.py index d6c88b5e8b4e..f71f78ac57c4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/operations/_operations.py @@ -17,12 +17,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from ..._configuration import BasicClientConfiguration from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -76,11 +75,11 @@ def simple(self, body: _models1.User, *, content_type: str = "application/json", """ @overload - def simple(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def simple(self, body: _types_models1.User, *, content_type: str = "application/json", **kwargs: Any) -> None: """simple. :param body: Required. - :type body: JSON + :type body: ~parameters.basic.explicitbody.types.User :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -104,12 +103,13 @@ def simple(self, body: IO[bytes], *, content_type: str = "application/json", **k """ def simple( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.User, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.User, _types_models1.User, IO[bytes]], **kwargs: Any ) -> None: """simple. - :param body: Is one of the following types: User, JSON, IO[bytes] Required. - :type body: ~parameters.basic.explicitbody.models.User or JSON or IO[bytes] + :param body: Is either a User type or a IO[bytes] type. Required. + :type body: ~parameters.basic.explicitbody.models.User or + ~parameters.basic.explicitbody.types.User or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/explicitbody/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/aio/operations/_operations.py index ef2d7315938c..05af2bef21a7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/aio/operations/_operations.py @@ -17,6 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict +from ... import types as _types_models2 from ...._utils.model_base import SdkJSONEncoder from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import BasicClientConfiguration @@ -60,11 +61,13 @@ async def simple(self, *, name: str, content_type: str = "application/json", **k """ @overload - async def simple(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def simple( + self, body: _types_models2.SimpleRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """simple. :param body: Required. - :type body: JSON + :type body: ~parameters.basic.implicitbody.types.SimpleRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -87,11 +90,13 @@ async def simple(self, body: IO[bytes], *, content_type: str = "application/json :raises ~corehttp.exceptions.HttpResponseError: """ - async def simple(self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any) -> None: + async def simple( + self, body: Union[JSON, _types_models2.SimpleRequest, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + ) -> None: """simple. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SimpleRequest, IO[bytes] Required. + :type body: JSON or ~parameters.basic.implicitbody.types.SimpleRequest or IO[bytes] :keyword name: Required. :paramtype name: str :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/models/__init__.py new file mode 100644 index 000000000000..e895c08ad4bc --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/models/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/models/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/models/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/operations/_operations.py index 3058077739ef..300942c2aa66 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/operations/_operations.py @@ -17,6 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict +from .. import types as _types_models1 from ..._configuration import BasicClientConfiguration from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer @@ -76,11 +77,13 @@ def simple(self, *, name: str, content_type: str = "application/json", **kwargs: """ @overload - def simple(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def simple( + self, body: _types_models1.SimpleRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """simple. :param body: Required. - :type body: JSON + :type body: ~parameters.basic.implicitbody.types.SimpleRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -104,12 +107,12 @@ def simple(self, body: IO[bytes], *, content_type: str = "application/json", **k """ def simple( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, body: Union[JSON, _types_models1.SimpleRequest, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any ) -> None: """simple. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SimpleRequest, IO[bytes] Required. + :type body: JSON or ~parameters.basic.implicitbody.types.SimpleRequest or IO[bytes] :keyword name: Required. :paramtype name: str :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/types.py new file mode 100644 index 000000000000..57e373cf3574 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/parameters/basic/implicitbody/types.py @@ -0,0 +1,14 @@ +# coding=utf-8 + +from typing_extensions import Required, TypedDict + + +class SimpleRequest(TypedDict, total=False): + """SimpleRequest. + + :ivar name: Required. + :vartype name: str + """ + + name: Required[str] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/pyproject.toml index 88bfa62d9667..df39260acb5c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-basic/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_operations/_operations.py index 1b39432f24a9..27f709068ce2 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_operations/_operations.py @@ -17,7 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from .._configuration import BodyOptionalityClientConfiguration from .._utils.model_base import SdkJSONEncoder from .._utils.serialization import Serializer @@ -81,11 +81,13 @@ def required_explicit( """ @overload - def required_explicit(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def required_explicit( + self, body: _types_models1.BodyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """required_explicit. :param body: Required. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -109,12 +111,13 @@ def required_explicit(self, body: IO[bytes], *, content_type: str = "application """ def required_explicit( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.BodyModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.BodyModel, _types_models1.BodyModel, IO[bytes]], **kwargs: Any ) -> None: """required_explicit. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Required. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Required. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -178,11 +181,13 @@ def required_implicit(self, *, name: str, content_type: str = "application/json" """ @overload - def required_implicit(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def required_implicit( + self, body: _types_models1.BodyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """required_implicit. :param body: Required. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -206,12 +211,12 @@ def required_implicit(self, body: IO[bytes], *, content_type: str = "application """ def required_implicit( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, body: Union[JSON, _types_models1.BodyModel, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any ) -> None: """required_implicit. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BodyModel, IO[bytes] Required. + :type body: JSON or ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :keyword name: Required. :paramtype name: str :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_operations.py index 5d904c6a02b3..06ab8f797021 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_operations.py @@ -17,7 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..._operations._operations import ( build_body_optionality_required_explicit_request, build_body_optionality_required_implicit_request, @@ -53,11 +53,13 @@ async def required_explicit( """ @overload - async def required_explicit(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def required_explicit( + self, body: _types_models2.BodyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """required_explicit. :param body: Required. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -82,11 +84,14 @@ async def required_explicit( :raises ~corehttp.exceptions.HttpResponseError: """ - async def required_explicit(self, body: Union[_models2.BodyModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def required_explicit( + self, body: Union[_models2.BodyModel, _types_models2.BodyModel, IO[bytes]], **kwargs: Any + ) -> None: """required_explicit. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Required. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Required. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -152,11 +157,13 @@ async def required_implicit(self, *, name: str, content_type: str = "application """ @overload - async def required_implicit(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def required_implicit( + self, body: _types_models2.BodyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """required_implicit. :param body: Required. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -182,12 +189,12 @@ async def required_implicit( """ async def required_implicit( - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, body: Union[JSON, _types_models2.BodyModel, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any ) -> None: """required_implicit. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BodyModel, IO[bytes] Required. + :type body: JSON or ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :keyword name: Required. :paramtype name: str :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_operations.py index d3d12890772d..58b136360f84 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_operations.py @@ -17,13 +17,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .... import models as _models3 +from .... import models as _models3, types as _types_models3 from ...._utils.model_base import SdkJSONEncoder from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import BodyOptionalityClientConfiguration from ...operations._operations import build_optional_explicit_omit_request, build_optional_explicit_set_request -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -62,11 +61,13 @@ async def set( """ @overload - async def set(self, body: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def set( + self, body: Optional[_types_models3.BodyModel] = None, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """set. :param body: Default value is None. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -91,11 +92,14 @@ async def set( :raises ~corehttp.exceptions.HttpResponseError: """ - async def set(self, body: Optional[Union[_models3.BodyModel, JSON, IO[bytes]]] = None, **kwargs: Any) -> None: + async def set( + self, body: Optional[Union[_models3.BodyModel, _types_models3.BodyModel, IO[bytes]]] = None, **kwargs: Any + ) -> None: """set. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Default value is None. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Default value is None. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -165,11 +169,13 @@ async def omit( """ @overload - async def omit(self, body: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def omit( + self, body: Optional[_types_models3.BodyModel] = None, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """omit. :param body: Default value is None. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -194,11 +200,14 @@ async def omit( :raises ~corehttp.exceptions.HttpResponseError: """ - async def omit(self, body: Optional[Union[_models3.BodyModel, JSON, IO[bytes]]] = None, **kwargs: Any) -> None: + async def omit( + self, body: Optional[Union[_models3.BodyModel, _types_models3.BodyModel, IO[bytes]]] = None, **kwargs: Any + ) -> None: """omit. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Default value is None. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Default value is None. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_operations.py index 61670a8ec1dc..622f6ea4d651 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_operations.py @@ -17,12 +17,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..._configuration import BodyOptionalityClientConfiguration from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -92,11 +91,13 @@ def set( """ @overload - def set(self, body: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any) -> None: + def set( + self, body: Optional[_types_models2.BodyModel] = None, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """set. :param body: Default value is None. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -120,12 +121,13 @@ def set(self, body: Optional[IO[bytes]] = None, *, content_type: str = "applicat """ def set( # pylint: disable=inconsistent-return-statements - self, body: Optional[Union[_models2.BodyModel, JSON, IO[bytes]]] = None, **kwargs: Any + self, body: Optional[Union[_models2.BodyModel, _types_models2.BodyModel, IO[bytes]]] = None, **kwargs: Any ) -> None: """set. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Default value is None. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Default value is None. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -195,11 +197,13 @@ def omit( """ @overload - def omit(self, body: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any) -> None: + def omit( + self, body: Optional[_types_models2.BodyModel] = None, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """omit. :param body: Default value is None. - :type body: JSON + :type body: ~parameters.bodyoptionality.types.BodyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -223,12 +227,13 @@ def omit(self, body: Optional[IO[bytes]] = None, *, content_type: str = "applica """ def omit( # pylint: disable=inconsistent-return-statements - self, body: Optional[Union[_models2.BodyModel, JSON, IO[bytes]]] = None, **kwargs: Any + self, body: Optional[Union[_models2.BodyModel, _types_models2.BodyModel, IO[bytes]]] = None, **kwargs: Any ) -> None: """omit. - :param body: Is one of the following types: BodyModel, JSON, IO[bytes] Default value is None. - :type body: ~parameters.bodyoptionality.models.BodyModel or JSON or IO[bytes] + :param body: Is either a BodyModel type or a IO[bytes] type. Default value is None. + :type body: ~parameters.bodyoptionality.models.BodyModel or + ~parameters.bodyoptionality.types.BodyModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/parameters/bodyoptionality/optionalexplicit/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/pyproject.toml index 39fb1827486a..8e1ea09c2cbc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-optionality/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/CHANGELOG.md new file mode 100644 index 000000000000..b957b2575b48 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (1970-01-01) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/MANIFEST.in b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/MANIFEST.in new file mode 100644 index 000000000000..d4bf7087fae0 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/MANIFEST.in @@ -0,0 +1,6 @@ +include *.md +include LICENSE +include parameters/bodyroot/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include parameters/__init__.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/README.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/__init__.py new file mode 100644 index 000000000000..906600cfd52e --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import BodyRootClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BodyRootClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_client.py new file mode 100644 index 000000000000..772c07540234 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_client.py @@ -0,0 +1,84 @@ +# coding=utf-8 + +from copy import deepcopy +import sys +from typing import Any + +from corehttp.rest import HttpRequest, HttpResponse +from corehttp.runtime import PipelineClient, policies + +from ._configuration import BodyRootClientConfiguration +from ._operations import _BodyRootClientOperationsMixin +from ._utils.serialization import Deserializer, Serializer + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + + +class BodyRootClient(_BodyRootClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """Test for @bodyRoot parameter patterns. + + :keyword endpoint: Service host. Default value is "http://localhost:3000". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "http://localhost:3000", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = BodyRootClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.retry_policy, + self._config.authentication_policy, + self._config.logging_policy, + ] + self._client: PipelineClient = PipelineClient(endpoint=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from corehttp.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~corehttp.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~corehttp.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_configuration.py new file mode 100644 index 000000000000..26d97ce52bbf --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_configuration.py @@ -0,0 +1,33 @@ +# coding=utf-8 + +from typing import Any + +from corehttp.runtime import policies + +from ._version import VERSION + + +class BodyRootClientConfiguration: + """Configuration for BodyRootClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "http://localhost:3000". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "parameters-bodyroot/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_operations/__init__.py similarity index 87% rename from eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_operations/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_operations/__init__.py index 87946fdeb71f..9fe04550f73f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_operations/__init__.py @@ -6,7 +6,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import _PageableClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import _BodyRootClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_operations/_operations.py new file mode 100644 index 000000000000..b02eeca17502 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_operations/_operations.py @@ -0,0 +1,151 @@ +# coding=utf-8 +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from corehttp.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from corehttp.rest import HttpRequest, HttpResponse +from corehttp.runtime import PipelineClient +from corehttp.runtime.pipeline import PipelineResponse +from corehttp.utils import case_insensitive_dict + +from .. import models as _models, types as _types +from .._configuration import BodyRootClientConfiguration +from .._utils.model_base import SdkJSONEncoder +from .._utils.serialization import Serializer +from .._utils.utils import ClientMixinABC + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_body_root_nested_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/parameters/body-root/nested" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +class _BodyRootClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], BodyRootClientConfiguration] +): + + @overload + def nested( + self, body_root_parameters: _models.BodyRootModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: ~parameters.bodyroot.models.BodyRootModel + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def nested( + self, body_root_parameters: _types.BodyRootModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: ~parameters.bodyroot.types.BodyRootModel + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def nested(self, body_root_parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def nested( # pylint: disable=inconsistent-return-statements + self, body_root_parameters: Union[_models.BodyRootModel, _types.BodyRootModel, IO[bytes]], **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Is either a BodyRootModel type or a IO[bytes] type. Required. + :type body_root_parameters: ~parameters.bodyroot.models.BodyRootModel or + ~parameters.bodyroot.types.BodyRootModel or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body_root_parameters, (IOBase, bytes)): + _content = body_root_parameters + else: + _content = json.dumps(body_root_parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_body_root_nested_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_operations/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_operations/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_utils/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_utils/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_utils/model_base.py new file mode 100644 index 000000000000..972617ba9ad8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_utils/model_base.py @@ -0,0 +1,1765 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +import isodate +from corehttp.exceptions import DeserializationError +from corehttp.utils import CaseInsensitiveEnumMeta +from corehttp.runtime.pipeline import PipelineResponse +from corehttp.serialization import _Null + +from corehttp.rest import HttpResponse + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on the mapping's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on the mapping's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: a set-like object providing a view on the mapping's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: The value for key if key is in the dictionary, else default. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if the dictionary is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from the dictionary. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Update the dictionary from a mapping or an iterable of key-value pairs. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: The value for key if key is in the dictionary, else default. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _serialize_duration(o, format) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass: dict[str, typing.Any] = {} + if args: + if isinstance(args[0], ET.Element): + dict_to_pass.update(self._init_from_xml(args[0])) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) + super().__init__(dict_to_pass) + + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + self, element: ET.Element + ) -> dict[str, typing.Any]: + """Deserialize an XML element into a dict mapping rest field names to values. + + :param ET.Element element: The XML element to deserialize from. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + existed_attr_keys: list[str] = [] + + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value.text if isinstance(value, ET.Element) else value) + except ValueError: + # for unknown value, return raw value + return value.text if isinstance(value, ET.Element) else value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +# pylint: disable=too-many-instance-attributes +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._is_optional = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + self._deserializer = deserializer + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + deserializer=deserializer, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) + wrapped_element = _create_xml_element( + element_name, + model_meta.get("prefix"), + _model_ns, + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + _set_xml_attribute(wrapped_element, k, v, prop_meta) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": _dict_ns, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": _items_ns, + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + _safe_register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_utils/serialization.py new file mode 100644 index 000000000000..4172d811ae21 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_utils/serialization.py @@ -0,0 +1,2169 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from corehttp.exceptions import DeserializationError, SerializationError +from corehttp.serialization import NULL as CoreNull + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_utils/utils.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_utils/utils.py similarity index 100% rename from eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_utils/utils.py rename to eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_utils/utils.py diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_version.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_version.py new file mode 100644 index 000000000000..9f6458b8cdac --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/_version.py @@ -0,0 +1,3 @@ +# coding=utf-8 + +VERSION = "1.0.0b1" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/__init__.py new file mode 100644 index 000000000000..bd2e1d7a5b7f --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import BodyRootClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BodyRootClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_client.py new file mode 100644 index 000000000000..c3e81e150b6e --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_client.py @@ -0,0 +1,86 @@ +# coding=utf-8 + +from copy import deepcopy +import sys +from typing import Any, Awaitable + +from corehttp.rest import AsyncHttpResponse, HttpRequest +from corehttp.runtime import AsyncPipelineClient, policies + +from .._utils.serialization import Deserializer, Serializer +from ._configuration import BodyRootClientConfiguration +from ._operations import _BodyRootClientOperationsMixin + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + + +class BodyRootClient(_BodyRootClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """Test for @bodyRoot parameter patterns. + + :keyword endpoint: Service host. Default value is "http://localhost:3000". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "http://localhost:3000", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = BodyRootClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.retry_policy, + self._config.authentication_policy, + self._config.logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(endpoint=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from corehttp.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~corehttp.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~corehttp.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_configuration.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_configuration.py new file mode 100644 index 000000000000..d05676d0d9e5 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_configuration.py @@ -0,0 +1,33 @@ +# coding=utf-8 + +from typing import Any + +from corehttp.runtime import policies + +from .._version import VERSION + + +class BodyRootClientConfiguration: + """Configuration for BodyRootClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "http://localhost:3000". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "parameters-bodyroot/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_operations/__init__.py similarity index 87% rename from eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_operations/__init__.py rename to eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_operations/__init__.py index 87946fdeb71f..9fe04550f73f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_operations/__init__.py @@ -6,7 +6,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import _PageableClientOperationsMixin # type: ignore # pylint: disable=unused-import +from ._operations import _BodyRootClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_operations/_operations.py new file mode 100644 index 000000000000..a6ee1ed00fd6 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_operations/_operations.py @@ -0,0 +1,138 @@ +# coding=utf-8 +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from corehttp.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from corehttp.rest import AsyncHttpResponse, HttpRequest +from corehttp.runtime import AsyncPipelineClient +from corehttp.runtime.pipeline import PipelineResponse +from corehttp.utils import case_insensitive_dict + +from ... import models as _models, types as _types +from ..._operations._operations import build_body_root_nested_request +from ..._utils.model_base import SdkJSONEncoder +from ..._utils.utils import ClientMixinABC +from .._configuration import BodyRootClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class _BodyRootClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], BodyRootClientConfiguration] +): + + @overload + async def nested( + self, body_root_parameters: _models.BodyRootModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: ~parameters.bodyroot.models.BodyRootModel + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def nested( + self, body_root_parameters: _types.BodyRootModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: ~parameters.bodyroot.types.BodyRootModel + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def nested( + self, body_root_parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Required. + :type body_root_parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def nested( + self, body_root_parameters: Union[_models.BodyRootModel, _types.BodyRootModel, IO[bytes]], **kwargs: Any + ) -> None: + """nested. + + :param body_root_parameters: Is either a BodyRootModel type or a IO[bytes] type. Required. + :type body_root_parameters: ~parameters.bodyroot.models.BodyRootModel or + ~parameters.bodyroot.types.BodyRootModel or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body_root_parameters, (IOBase, bytes)): + _content = body_root_parameters + else: + _content = json.dumps(body_root_parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_body_root_nested_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run( # type: ignore + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_operations/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_operations/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/aio/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/models/__init__.py new file mode 100644 index 000000000000..b2273b4a8f02 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/models/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + BodyRootModel, + NestedParameterBody, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BodyRootModel", + "NestedParameterBody", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/models/_models.py new file mode 100644 index 000000000000..a1ab5e1772bc --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/models/_models.py @@ -0,0 +1,76 @@ +# coding=utf-8 +# pylint: disable=useless-super-delegation + +from typing import Any, Mapping, Optional, TYPE_CHECKING, overload + +from .._utils.model_base import Model as _Model, rest_field + +if TYPE_CHECKING: + from .. import models as _models + + +class BodyRootModel(_Model): + """BodyRootModel. + + :ivar category: + :vartype category: str + :ivar link_type: + :vartype link_type: str + :ivar was_successful: + :vartype was_successful: bool + """ + + category: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + link_type: Optional[str] = rest_field(name="linkType", visibility=["read", "create", "update", "delete", "query"]) + was_successful: Optional[bool] = rest_field( + name="wasSuccessful", visibility=["read", "create", "update", "delete", "query"] + ) + + @overload + def __init__( + self, + *, + category: Optional[str] = None, + link_type: Optional[str] = None, + was_successful: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NestedParameterBody(_Model): + """NestedParameterBody. + + :ivar body_root_parameters: Required. + :vartype body_root_parameters: ~parameters.bodyroot.models.BodyRootModel + """ + + body_root_parameters: "_models.BodyRootModel" = rest_field( + name="bodyRootParameters", visibility=["read", "create", "update", "delete", "query"] + ) + """Required.""" + + @overload + def __init__( + self, + *, + body_root_parameters: "_models.BodyRootModel", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/models/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/models/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/py.typed b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/types.py new file mode 100644 index 000000000000..d66591b4d5aa --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/parameters/bodyroot/types.py @@ -0,0 +1,30 @@ +# coding=utf-8 + +from typing_extensions import Required, TypedDict + + +class BodyRootModel(TypedDict, total=False): + """BodyRootModel. + + :ivar category: + :vartype category: str + :ivar link_type: + :vartype link_type: str + :ivar was_successful: + :vartype was_successful: bool + """ + + category: str + linkType: str + wasSuccessful: bool + + +class NestedParameterBody(TypedDict, total=False): + """NestedParameterBody. + + :ivar body_root_parameters: Required. + :vartype body_root_parameters: "BodyRootModel" + """ + + bodyRootParameters: Required["BodyRootModel"] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/pyproject.toml new file mode 100644 index 000000000000..8b023c277757 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-body-root/pyproject.toml @@ -0,0 +1,50 @@ + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "parameters-bodyroot" +authors = [ + { name = "" }, +] +description = " Parameters Bodyroot Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", +] +requires-python = ">=3.10" + +dependencies = [ + "isodate>=0.6.1", + "corehttp[requests]>=1.0.0b6", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[tool.setuptools.dynamic] +version = {attr = "parameters.bodyroot._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "parameters", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/header/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/header/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/header/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/header/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/header/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/header/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/header/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/header/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/query/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/query/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/query/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/query/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/query/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/query/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/query/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/parameters/collectionformat/query/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/pyproject.toml index 950933d444d4..475a048b652f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-collection-format/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/parameters/path/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/pyproject.toml index 292395fb03a9..4d7d57b44144 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-path/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_client.py index a4bb9e32ce17..5f732a1a5b03 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_client.py @@ -9,7 +9,7 @@ from ._configuration import QueryClientConfiguration from ._utils.serialization import Deserializer, Serializer -from .operations import ConstantOperations +from .operations import ConstantOperations, SpecialCharOperations if sys.version_info >= (3, 11): from typing import Self @@ -22,6 +22,8 @@ class QueryClient: # pylint: disable=client-accepts-api-version-keyword :ivar constant: ConstantOperations operations :vartype constant: parameters.query.operations.ConstantOperations + :ivar special_char: SpecialCharOperations operations + :vartype special_char: parameters.query.operations.SpecialCharOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -49,6 +51,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._deserialize = Deserializer() self._serialize.client_side_validation = False self.constant = ConstantOperations(self._client, self._config, self._serialize, self._deserialize) + self.special_char = SpecialCharOperations(self._client, self._config, self._serialize, self._deserialize) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/_client.py index bf9583fa41d8..cc94f8e48d0f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/_client.py @@ -9,7 +9,7 @@ from .._utils.serialization import Deserializer, Serializer from ._configuration import QueryClientConfiguration -from .operations import ConstantOperations +from .operations import ConstantOperations, SpecialCharOperations if sys.version_info >= (3, 11): from typing import Self @@ -22,6 +22,8 @@ class QueryClient: # pylint: disable=client-accepts-api-version-keyword :ivar constant: ConstantOperations operations :vartype constant: parameters.query.aio.operations.ConstantOperations + :ivar special_char: SpecialCharOperations operations + :vartype special_char: parameters.query.aio.operations.SpecialCharOperations :keyword endpoint: Service host. Default value is "http://localhost:3000". :paramtype endpoint: str """ @@ -49,6 +51,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._deserialize = Deserializer() self._serialize.client_side_validation = False self.constant = ConstantOperations(self._client, self._config, self._serialize, self._deserialize) + self.special_char = SpecialCharOperations(self._client, self._config, self._serialize, self._deserialize) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/__init__.py index 2c4278d4d156..ab2a4c896b11 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/__init__.py @@ -7,6 +7,7 @@ from ._patch import * # pylint: disable=unused-wildcard-import from ._operations import ConstantOperations # type: ignore +from ._operations import SpecialCharOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -14,6 +15,7 @@ __all__ = [ "ConstantOperations", + "SpecialCharOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/_operations.py index 73b085eeb766..7e50b3f5b61e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/_operations.py @@ -15,7 +15,7 @@ from corehttp.runtime.pipeline import PipelineResponse from ..._utils.serialization import Deserializer, Serializer -from ...operations._operations import build_constant_post_request +from ...operations._operations import build_constant_post_request, build_special_char_dollar_sign_request from .._configuration import QueryClientConfiguration T = TypeVar("T") @@ -81,3 +81,65 @@ async def post(self, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore + + +class SpecialCharOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~parameters.query.aio.QueryClient`'s + :attr:`special_char` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueryClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def dollar_sign(self, *, filter: str, **kwargs: Any) -> None: + """dollar_sign. + + :keyword filter: Required. + :paramtype filter: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_special_char_dollar_sign_request( + filter=filter, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/aio/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/__init__.py index 2c4278d4d156..ab2a4c896b11 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/__init__.py @@ -7,6 +7,7 @@ from ._patch import * # pylint: disable=unused-wildcard-import from ._operations import ConstantOperations # type: ignore +from ._operations import SpecialCharOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -14,6 +15,7 @@ __all__ = [ "ConstantOperations", + "SpecialCharOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/_operations.py index 2a4cbd135264..3be00ad4be76 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/_operations.py @@ -38,6 +38,18 @@ def build_constant_post_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, **kwargs) +def build_special_char_dollar_sign_request(*, filter: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/parameters/query/special-char/dollar-sign" + + # Construct parameters + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + class ConstantOperations: """ .. warning:: @@ -97,3 +109,65 @@ def post(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-st if cls: return cls(pipeline_response, None, {}) # type: ignore + + +class SpecialCharOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~parameters.query.QueryClient`'s + :attr:`special_char` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueryClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def dollar_sign(self, *, filter: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """dollar_sign. + + :keyword filter: Required. + :paramtype filter: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_special_char_dollar_sign_request( + filter=filter, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/parameters/query/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/pyproject.toml index 5b1ca92a2d47..e8521e18f5ce 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-query/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/aio/operations/_operations.py index 471a358aca02..ecee0c8c7981 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/aio/operations/_operations.py @@ -17,6 +17,8 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict +from ... import types as _types_models2 +from .... import types as _types_models3 from ...._utils.model_base import SdkJSONEncoder from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import SpreadClientConfiguration @@ -67,12 +69,12 @@ async def spread_as_request_body(self, *, name: str, content_type: str = "applic @overload async def spread_as_request_body( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.SpreadAsRequestBodyRequest, *, content_type: str = "application/json", **kwargs: Any ) -> None: """spread_as_request_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.alias.types.SpreadAsRequestBodyRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -98,12 +100,17 @@ async def spread_as_request_body( """ async def spread_as_request_body( - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, + body: Union[JSON, _types_models2.SpreadAsRequestBodyRequest, IO[bytes]] = _Unset, + *, + name: str = _Unset, + **kwargs: Any ) -> None: """spread_as_request_body. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadAsRequestBodyRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.alias.types.SpreadAsRequestBodyRequest or IO[bytes] :keyword name: Required. :paramtype name: str :return: None @@ -181,14 +188,20 @@ async def spread_parameter_with_inner_model( @overload async def spread_parameter_with_inner_model( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types_models3.SpreadParameterWithInnerModelRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_parameter_with_inner_model. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadParameterWithInnerModelRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -222,7 +235,7 @@ async def spread_parameter_with_inner_model( async def spread_parameter_with_inner_model( self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types_models3.SpreadParameterWithInnerModelRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -232,8 +245,9 @@ async def spread_parameter_with_inner_model( :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadParameterWithInnerModelRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadParameterWithInnerModelRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: Required. @@ -315,14 +329,20 @@ async def spread_as_request_parameter( @overload async def spread_as_request_parameter( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types_models3.SpreadAsRequestParameterRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_as_request_parameter. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadAsRequestParameterRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -356,7 +376,7 @@ async def spread_as_request_parameter( async def spread_as_request_parameter( self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types_models3.SpreadAsRequestParameterRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -366,8 +386,9 @@ async def spread_as_request_parameter( :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadAsRequestParameterRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.types.SpreadAsRequestParameterRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: Required. @@ -464,14 +485,20 @@ async def spread_with_multiple_parameters( @overload async def spread_with_multiple_parameters( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types_models3.SpreadWithMultipleParametersRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_with_multiple_parameters. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadWithMultipleParametersRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -505,7 +532,7 @@ async def spread_with_multiple_parameters( async def spread_with_multiple_parameters( self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types_models3.SpreadWithMultipleParametersRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, required_string: str = _Unset, @@ -518,8 +545,9 @@ async def spread_with_multiple_parameters( :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadWithMultipleParametersRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadWithMultipleParametersRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword required_string: required string. Required. @@ -623,14 +651,20 @@ async def spread_parameter_with_inner_alias( @overload async def spread_parameter_with_inner_alias( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types_models3.SpreadParameterWithInnerAliasRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread an alias with contains another alias property as body. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadParameterWithInnerAliasRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -664,7 +698,7 @@ async def spread_parameter_with_inner_alias( async def spread_parameter_with_inner_alias( self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types_models3.SpreadParameterWithInnerAliasRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -675,8 +709,9 @@ async def spread_parameter_with_inner_alias( :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadParameterWithInnerAliasRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadParameterWithInnerAliasRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: name of the Thing. Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/models/__init__.py new file mode 100644 index 000000000000..e895c08ad4bc --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/models/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/models/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/models/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/operations/_operations.py index 80d4b7522545..9298b4b13b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/operations/_operations.py @@ -17,6 +17,8 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict +from .. import types as _types_models1 +from ... import types as _types_models2 from ..._configuration import SpreadClientConfiguration from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer @@ -164,11 +166,13 @@ def spread_as_request_body(self, *, name: str, content_type: str = "application/ """ @overload - def spread_as_request_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def spread_as_request_body( + self, body: _types_models1.SpreadAsRequestBodyRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """spread_as_request_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.alias.types.SpreadAsRequestBodyRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -192,12 +196,17 @@ def spread_as_request_body(self, body: IO[bytes], *, content_type: str = "applic """ def spread_as_request_body( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, + body: Union[JSON, _types_models1.SpreadAsRequestBodyRequest, IO[bytes]] = _Unset, + *, + name: str = _Unset, + **kwargs: Any ) -> None: """spread_as_request_body. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadAsRequestBodyRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.alias.types.SpreadAsRequestBodyRequest or IO[bytes] :keyword name: Required. :paramtype name: str :return: None @@ -275,14 +284,20 @@ def spread_parameter_with_inner_model( @overload def spread_parameter_with_inner_model( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types_models2.SpreadParameterWithInnerModelRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_parameter_with_inner_model. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadParameterWithInnerModelRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -316,7 +331,7 @@ def spread_parameter_with_inner_model( def spread_parameter_with_inner_model( # pylint: disable=inconsistent-return-statements self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types_models2.SpreadParameterWithInnerModelRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -326,8 +341,9 @@ def spread_parameter_with_inner_model( # pylint: disable=inconsistent-return-st :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadParameterWithInnerModelRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadParameterWithInnerModelRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: Required. @@ -409,14 +425,20 @@ def spread_as_request_parameter( @overload def spread_as_request_parameter( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types_models2.SpreadAsRequestParameterRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_as_request_parameter. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadAsRequestParameterRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -450,7 +472,7 @@ def spread_as_request_parameter( def spread_as_request_parameter( # pylint: disable=inconsistent-return-statements self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types_models2.SpreadAsRequestParameterRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -460,8 +482,9 @@ def spread_as_request_parameter( # pylint: disable=inconsistent-return-statemen :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadAsRequestParameterRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.types.SpreadAsRequestParameterRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: Required. @@ -558,14 +581,20 @@ def spread_with_multiple_parameters( @overload def spread_with_multiple_parameters( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types_models2.SpreadWithMultipleParametersRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_with_multiple_parameters. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadWithMultipleParametersRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -599,7 +628,7 @@ def spread_with_multiple_parameters( def spread_with_multiple_parameters( # pylint: disable=inconsistent-return-statements self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types_models2.SpreadWithMultipleParametersRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, required_string: str = _Unset, @@ -612,8 +641,9 @@ def spread_with_multiple_parameters( # pylint: disable=inconsistent-return-stat :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadWithMultipleParametersRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadWithMultipleParametersRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword required_string: required string. Required. @@ -717,14 +747,20 @@ def spread_parameter_with_inner_alias( @overload def spread_parameter_with_inner_alias( - self, id: str, body: JSON, *, x_ms_test_header: str, content_type: str = "application/json", **kwargs: Any + self, + id: str, + body: _types_models2.SpreadParameterWithInnerAliasRequest, + *, + x_ms_test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread an alias with contains another alias property as body. :param id: Required. :type id: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadParameterWithInnerAliasRequest :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -758,7 +794,7 @@ def spread_parameter_with_inner_alias( def spread_parameter_with_inner_alias( # pylint: disable=inconsistent-return-statements self, id: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types_models2.SpreadParameterWithInnerAliasRequest, IO[bytes]] = _Unset, *, x_ms_test_header: str, name: str = _Unset, @@ -769,8 +805,9 @@ def spread_parameter_with_inner_alias( # pylint: disable=inconsistent-return-st :param id: Required. :type id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadParameterWithInnerAliasRequest, + IO[bytes] Required. + :type body: JSON or ~parameters.spread.types.SpreadParameterWithInnerAliasRequest or IO[bytes] :keyword x_ms_test_header: Required. :paramtype x_ms_test_header: str :keyword name: name of the Thing. Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/types.py new file mode 100644 index 000000000000..7a45a4c92041 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/alias/types.py @@ -0,0 +1,14 @@ +# coding=utf-8 + +from typing_extensions import Required, TypedDict + + +class SpreadAsRequestBodyRequest(TypedDict, total=False): + """SpreadAsRequestBodyRequest. + + :ivar name: Required. + :vartype name: str + """ + + name: Required[str] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/aio/operations/_operations.py index 4fb0a9a01d67..83725ec42575 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/aio/operations/_operations.py @@ -17,7 +17,8 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 +from .... import types as _types_models3 from ...._utils.model_base import SdkJSONEncoder from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import SpreadClientConfiguration @@ -68,12 +69,12 @@ async def spread_as_request_body(self, *, name: str, content_type: str = "applic @overload async def spread_as_request_body( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.BodyParameter, *, content_type: str = "application/json", **kwargs: Any ) -> None: """spread_as_request_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.model.types.BodyParameter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -99,12 +100,12 @@ async def spread_as_request_body( """ async def spread_as_request_body( - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, body: Union[JSON, _types_models2.BodyParameter, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any ) -> None: """spread_as_request_body. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BodyParameter, IO[bytes] Required. + :type body: JSON or ~parameters.spread.model.types.BodyParameter or IO[bytes] :keyword name: Required. :paramtype name: str :return: None @@ -178,12 +179,12 @@ async def spread_composite_request_only_with_body( @overload async def spread_composite_request_only_with_body( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.BodyParameter, *, content_type: str = "application/json", **kwargs: Any ) -> None: """spread_composite_request_only_with_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.model.types.BodyParameter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -209,12 +210,13 @@ async def spread_composite_request_only_with_body( """ async def spread_composite_request_only_with_body( - self, body: Union[_models2.BodyParameter, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models2.BodyParameter, _types_models2.BodyParameter, IO[bytes]], **kwargs: Any ) -> None: """spread_composite_request_only_with_body. - :param body: Is one of the following types: BodyParameter, JSON, IO[bytes] Required. - :type body: ~parameters.spread.model.models.BodyParameter or JSON or IO[bytes] + :param body: Is either a BodyParameter type or a IO[bytes] type. Required. + :type body: ~parameters.spread.model.models.BodyParameter or + ~parameters.spread.model.types.BodyParameter or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -338,14 +340,20 @@ async def spread_composite_request( @overload async def spread_composite_request( - self, name: str, body: JSON, *, test_header: str, content_type: str = "application/json", **kwargs: Any + self, + name: str, + body: _types_models2.BodyParameter, + *, + test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_composite_request. :param name: Required. :type name: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.model.types.BodyParameter :keyword test_header: Required. :paramtype test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -377,14 +385,20 @@ async def spread_composite_request( """ async def spread_composite_request( - self, name: str, body: Union[_models2.BodyParameter, JSON, IO[bytes]], *, test_header: str, **kwargs: Any + self, + name: str, + body: Union[_models2.BodyParameter, _types_models2.BodyParameter, IO[bytes]], + *, + test_header: str, + **kwargs: Any ) -> None: """spread_composite_request. :param name: Required. :type name: str - :param body: Is one of the following types: BodyParameter, JSON, IO[bytes] Required. - :type body: ~parameters.spread.model.models.BodyParameter or JSON or IO[bytes] + :param body: Is either a BodyParameter type or a IO[bytes] type. Required. + :type body: ~parameters.spread.model.models.BodyParameter or + ~parameters.spread.model.types.BodyParameter or IO[bytes] :keyword test_header: Required. :paramtype test_header: str :return: None @@ -459,14 +473,20 @@ async def spread_composite_request_mix( @overload async def spread_composite_request_mix( - self, name: str, body: JSON, *, test_header: str, content_type: str = "application/json", **kwargs: Any + self, + name: str, + body: _types_models3.SpreadCompositeRequestMixRequest, + *, + test_header: str, + content_type: str = "application/json", + **kwargs: Any ) -> None: """spread_composite_request_mix. :param name: Required. :type name: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadCompositeRequestMixRequest :keyword test_header: Required. :paramtype test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -498,14 +518,21 @@ async def spread_composite_request_mix( """ async def spread_composite_request_mix( - self, name: str, body: Union[JSON, IO[bytes]] = _Unset, *, test_header: str, prop: str = _Unset, **kwargs: Any + self, + name: str, + body: Union[JSON, _types_models3.SpreadCompositeRequestMixRequest, IO[bytes]] = _Unset, + *, + test_header: str, + prop: str = _Unset, + **kwargs: Any ) -> None: """spread_composite_request_mix. :param name: Required. :type name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadCompositeRequestMixRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.types.SpreadCompositeRequestMixRequest or IO[bytes] :keyword test_header: Required. :paramtype test_header: str :keyword prop: Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/operations/_operations.py index d58bae8d1dd2..b493bbb1592f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/operations/_operations.py @@ -17,7 +17,8 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 +from ... import types as _types_models2 from ..._configuration import SpreadClientConfiguration from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer @@ -156,11 +157,13 @@ def spread_as_request_body(self, *, name: str, content_type: str = "application/ """ @overload - def spread_as_request_body(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def spread_as_request_body( + self, body: _types_models1.BodyParameter, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """spread_as_request_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.model.types.BodyParameter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -184,12 +187,12 @@ def spread_as_request_body(self, body: IO[bytes], *, content_type: str = "applic """ def spread_as_request_body( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any + self, body: Union[JSON, _types_models1.BodyParameter, IO[bytes]] = _Unset, *, name: str = _Unset, **kwargs: Any ) -> None: """spread_as_request_body. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BodyParameter, IO[bytes] Required. + :type body: JSON or ~parameters.spread.model.types.BodyParameter or IO[bytes] :keyword name: Required. :paramtype name: str :return: None @@ -263,12 +266,12 @@ def spread_composite_request_only_with_body( @overload def spread_composite_request_only_with_body( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models1.BodyParameter, *, content_type: str = "application/json", **kwargs: Any ) -> None: """spread_composite_request_only_with_body. :param body: Required. - :type body: JSON + :type body: ~parameters.spread.model.types.BodyParameter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -294,12 +297,13 @@ def spread_composite_request_only_with_body( """ def spread_composite_request_only_with_body( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.BodyParameter, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.BodyParameter, _types_models1.BodyParameter, IO[bytes]], **kwargs: Any ) -> None: """spread_composite_request_only_with_body. - :param body: Is one of the following types: BodyParameter, JSON, IO[bytes] Required. - :type body: ~parameters.spread.model.models.BodyParameter or JSON or IO[bytes] + :param body: Is either a BodyParameter type or a IO[bytes] type. Required. + :type body: ~parameters.spread.model.models.BodyParameter or + ~parameters.spread.model.types.BodyParameter or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -425,14 +429,20 @@ def spread_composite_request( @overload def spread_composite_request( - self, name: str, body: JSON, *, test_header: str, content_type: str = "application/json", **kwargs: Any + self, + name: str, + body: _types_models1.BodyParameter, + *, + test_header: str, + content_type: str = "application/json", + **kwargs: Any, ) -> None: """spread_composite_request. :param name: Required. :type name: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.model.types.BodyParameter :keyword test_header: Required. :paramtype test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -464,14 +474,20 @@ def spread_composite_request( """ def spread_composite_request( # pylint: disable=inconsistent-return-statements - self, name: str, body: Union[_models1.BodyParameter, JSON, IO[bytes]], *, test_header: str, **kwargs: Any + self, + name: str, + body: Union[_models1.BodyParameter, _types_models1.BodyParameter, IO[bytes]], + *, + test_header: str, + **kwargs: Any, ) -> None: """spread_composite_request. :param name: Required. :type name: str - :param body: Is one of the following types: BodyParameter, JSON, IO[bytes] Required. - :type body: ~parameters.spread.model.models.BodyParameter or JSON or IO[bytes] + :param body: Is either a BodyParameter type or a IO[bytes] type. Required. + :type body: ~parameters.spread.model.models.BodyParameter or + ~parameters.spread.model.types.BodyParameter or IO[bytes] :keyword test_header: Required. :paramtype test_header: str :return: None @@ -546,14 +562,20 @@ def spread_composite_request_mix( @overload def spread_composite_request_mix( - self, name: str, body: JSON, *, test_header: str, content_type: str = "application/json", **kwargs: Any + self, + name: str, + body: _types_models2.SpreadCompositeRequestMixRequest, + *, + test_header: str, + content_type: str = "application/json", + **kwargs: Any, ) -> None: """spread_composite_request_mix. :param name: Required. :type name: str :param body: Required. - :type body: JSON + :type body: ~parameters.spread.types.SpreadCompositeRequestMixRequest :keyword test_header: Required. :paramtype test_header: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -585,14 +607,21 @@ def spread_composite_request_mix( """ def spread_composite_request_mix( # pylint: disable=inconsistent-return-statements - self, name: str, body: Union[JSON, IO[bytes]] = _Unset, *, test_header: str, prop: str = _Unset, **kwargs: Any + self, + name: str, + body: Union[JSON, _types_models2.SpreadCompositeRequestMixRequest, IO[bytes]] = _Unset, + *, + test_header: str, + prop: str = _Unset, + **kwargs: Any, ) -> None: """spread_composite_request_mix. :param name: Required. :type name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SpreadCompositeRequestMixRequest, IO[bytes] + Required. + :type body: JSON or ~parameters.spread.types.SpreadCompositeRequestMixRequest or IO[bytes] :keyword test_header: Required. :paramtype test_header: str :keyword prop: Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/model/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/models/__init__.py new file mode 100644 index 000000000000..e895c08ad4bc --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/models/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/models/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/models/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/types.py new file mode 100644 index 000000000000..012f165ead11 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/parameters/spread/types.py @@ -0,0 +1,74 @@ +# coding=utf-8 + +from typing_extensions import Required, TypedDict + + +class SpreadCompositeRequestMixRequest(TypedDict, total=False): + """SpreadCompositeRequestMixRequest. + + :ivar prop: Required. + :vartype prop: str + """ + + prop: Required[str] + """Required.""" + + +class SpreadParameterWithInnerModelRequest(TypedDict, total=False): + """SpreadParameterWithInnerModelRequest. + + :ivar name: Required. + :vartype name: str + """ + + name: Required[str] + """Required.""" + + +class SpreadAsRequestParameterRequest(TypedDict, total=False): + """SpreadAsRequestParameterRequest. + + :ivar name: Required. + :vartype name: str + """ + + name: Required[str] + """Required.""" + + +class SpreadWithMultipleParametersRequest(TypedDict, total=False): + """SpreadWithMultipleParametersRequest. + + :ivar required_string: required string. Required. + :vartype required_string: str + :ivar optional_int: optional int. + :vartype optional_int: int + :ivar required_int_list: required int. Required. + :vartype required_int_list: list[int] + :ivar optional_string_list: optional string. + :vartype optional_string_list: list[str] + """ + + requiredString: Required[str] + """required string. Required.""" + optionalInt: int + """optional int.""" + requiredIntList: Required[list[int]] + """required int. Required.""" + optionalStringList: list[str] + """optional string.""" + + +class SpreadParameterWithInnerAliasRequest(TypedDict, total=False): + """SpreadParameterWithInnerAliasRequest. + + :ivar name: name of the Thing. Required. + :vartype name: str + :ivar age: age of the Thing. Required. + :vartype age: int + """ + + name: Required[str] + """name of the Thing. Required.""" + age: Required[int] + """age of the Thing. Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/pyproject.toml index efc5e459146d..e39ea89e12a5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/parameters-spread/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/types.py deleted file mode 100644 index 8d5f52e7d95a..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/differentbody/types.py +++ /dev/null @@ -1,14 +0,0 @@ -# coding=utf-8 - -from typing_extensions import Required, TypedDict - - -class PngImageAsJson(TypedDict, total=False): - """PngImageAsJson. - - :ivar content: Required. - :vartype content: bytes - """ - - content: Required[bytes] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/samebody/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/samebody/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/samebody/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/samebody/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/samebody/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/samebody/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/samebody/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/payload/contentnegotiation/samebody/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/pyproject.toml index 2c4d25c98725..1df704765a81 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-content-negotiation/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/aio/_operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/aio/_operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/aio/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/payload/head/aio/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/pyproject.toml index a3f1890c4eac..7b413a877c47 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-head/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_operations/_operations.py index c59dd43b236f..88471c396d3a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import JsonMergePatchClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -107,11 +106,13 @@ def create_resource( """ @overload - def create_resource(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Resource: + def create_resource( + self, body: _types.Resource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. :param body: Required. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.Resource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -136,11 +137,14 @@ def create_resource( :raises ~corehttp.exceptions.HttpResponseError: """ - def create_resource(self, body: Union[_models.Resource, JSON, IO[bytes]], **kwargs: Any) -> _models.Resource: + def create_resource( + self, body: Union[_models.Resource, _types.Resource, IO[bytes]], **kwargs: Any + ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. - :param body: Is one of the following types: Resource, JSON, IO[bytes] Required. - :type body: ~payload.jsonmergepatch.models.Resource or JSON or IO[bytes] + :param body: Is either a Resource type or a IO[bytes] type. Required. + :type body: ~payload.jsonmergepatch.models.Resource or ~payload.jsonmergepatch.types.Resource + or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~corehttp.exceptions.HttpResponseError: @@ -220,12 +224,12 @@ def update_resource( @overload def update_resource( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.ResourcePatch, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. :param body: Required. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.ResourcePatch :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -250,11 +254,14 @@ def update_resource( :raises ~corehttp.exceptions.HttpResponseError: """ - def update_resource(self, body: Union[_models.ResourcePatch, JSON, IO[bytes]], **kwargs: Any) -> _models.Resource: + def update_resource( + self, body: Union[_models.ResourcePatch, _types.ResourcePatch, IO[bytes]], **kwargs: Any + ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. - :param body: Is one of the following types: ResourcePatch, JSON, IO[bytes] Required. - :type body: ~payload.jsonmergepatch.models.ResourcePatch or JSON or IO[bytes] + :param body: Is either a ResourcePatch type or a IO[bytes] type. Required. + :type body: ~payload.jsonmergepatch.models.ResourcePatch or + ~payload.jsonmergepatch.types.ResourcePatch or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~corehttp.exceptions.HttpResponseError: @@ -338,12 +345,16 @@ def update_optional_resource( @overload def update_optional_resource( - self, body: Optional[JSON] = None, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: Optional[_types.ResourcePatch] = None, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any, ) -> _models.Resource: """Test content-type: application/merge-patch+json with optional body. :param body: Default value is None. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.ResourcePatch :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -369,13 +380,13 @@ def update_optional_resource( """ def update_optional_resource( - self, body: Optional[Union[_models.ResourcePatch, JSON, IO[bytes]]] = None, **kwargs: Any + self, body: Optional[Union[_models.ResourcePatch, _types.ResourcePatch, IO[bytes]]] = None, **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with optional body. - :param body: Is one of the following types: ResourcePatch, JSON, IO[bytes] Default value is - None. - :type body: ~payload.jsonmergepatch.models.ResourcePatch or JSON or IO[bytes] + :param body: Is either a ResourcePatch type or a IO[bytes] type. Default value is None. + :type body: ~payload.jsonmergepatch.models.ResourcePatch or + ~payload.jsonmergepatch.types.ResourcePatch or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_operations.py index 3560e53f0c3f..3e5fe085c0d9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_json_merge_patch_create_resource_request, build_json_merge_patch_update_optional_resource_request, @@ -29,7 +29,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import JsonMergePatchClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -56,12 +55,12 @@ async def create_resource( @overload async def create_resource( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.Resource, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. :param body: Required. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.Resource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -86,11 +85,14 @@ async def create_resource( :raises ~corehttp.exceptions.HttpResponseError: """ - async def create_resource(self, body: Union[_models.Resource, JSON, IO[bytes]], **kwargs: Any) -> _models.Resource: + async def create_resource( + self, body: Union[_models.Resource, _types.Resource, IO[bytes]], **kwargs: Any + ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. - :param body: Is one of the following types: Resource, JSON, IO[bytes] Required. - :type body: ~payload.jsonmergepatch.models.Resource or JSON or IO[bytes] + :param body: Is either a Resource type or a IO[bytes] type. Required. + :type body: ~payload.jsonmergepatch.models.Resource or ~payload.jsonmergepatch.types.Resource + or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~corehttp.exceptions.HttpResponseError: @@ -172,12 +174,12 @@ async def update_resource( @overload async def update_resource( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.ResourcePatch, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. :param body: Required. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.ResourcePatch :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -203,12 +205,13 @@ async def update_resource( """ async def update_resource( - self, body: Union[_models.ResourcePatch, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ResourcePatch, _types.ResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with required body. - :param body: Is one of the following types: ResourcePatch, JSON, IO[bytes] Required. - :type body: ~payload.jsonmergepatch.models.ResourcePatch or JSON or IO[bytes] + :param body: Is either a ResourcePatch type or a IO[bytes] type. Required. + :type body: ~payload.jsonmergepatch.models.ResourcePatch or + ~payload.jsonmergepatch.types.ResourcePatch or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~corehttp.exceptions.HttpResponseError: @@ -294,12 +297,16 @@ async def update_optional_resource( @overload async def update_optional_resource( - self, body: Optional[JSON] = None, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: Optional[_types.ResourcePatch] = None, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with optional body. :param body: Default value is None. - :type body: JSON + :type body: ~payload.jsonmergepatch.types.ResourcePatch :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -325,13 +332,13 @@ async def update_optional_resource( """ async def update_optional_resource( - self, body: Optional[Union[_models.ResourcePatch, JSON, IO[bytes]]] = None, **kwargs: Any + self, body: Optional[Union[_models.ResourcePatch, _types.ResourcePatch, IO[bytes]]] = None, **kwargs: Any ) -> _models.Resource: """Test content-type: application/merge-patch+json with optional body. - :param body: Is one of the following types: ResourcePatch, JSON, IO[bytes] Default value is - None. - :type body: ~payload.jsonmergepatch.models.ResourcePatch or JSON or IO[bytes] + :param body: Is either a ResourcePatch type or a IO[bytes] type. Default value is None. + :type body: ~payload.jsonmergepatch.models.ResourcePatch or + ~payload.jsonmergepatch.types.ResourcePatch or IO[bytes] :return: Resource. The Resource is compatible with MutableMapping :rtype: ~payload.jsonmergepatch.models.Resource :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/types.py index b762b6a5f009..af5a9c53a5c6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/payload/jsonmergepatch/types.py @@ -24,15 +24,15 @@ class Resource(TypedDict, total=False): :ivar description: :vartype description: str :ivar map: - :vartype map: dict[str, ~payload.jsonmergepatch.models.InnerModel] + :vartype map: dict[str, "InnerModel"] :ivar array: - :vartype array: list[~payload.jsonmergepatch.models.InnerModel] + :vartype array: list["InnerModel"] :ivar int_value: :vartype int_value: int :ivar float_value: :vartype float_value: float :ivar inner_model: - :vartype inner_model: ~payload.jsonmergepatch.models.InnerModel + :vartype inner_model: "InnerModel" :ivar int_array: :vartype int_array: list[int] """ @@ -54,15 +54,15 @@ class ResourcePatch(TypedDict, total=False): :ivar description: :vartype description: str :ivar map: - :vartype map: dict[str, ~payload.jsonmergepatch.models.InnerModel] + :vartype map: dict[str, "InnerModel"] :ivar array: - :vartype array: list[~payload.jsonmergepatch.models.InnerModel] + :vartype array: list["InnerModel"] :ivar int_value: :vartype int_value: int :ivar float_value: :vartype float_value: float :ivar inner_model: - :vartype inner_model: ~payload.jsonmergepatch.models.InnerModel + :vartype inner_model: "InnerModel" :ivar int_array: :vartype int_array: list[int] """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/pyproject.toml index a3505f3a8ef8..41b7c79c7864 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-json-merge-patch/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/stringbody/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/stringbody/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/stringbody/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/stringbody/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/stringbody/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/stringbody/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/stringbody/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/payload/mediatype/stringbody/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/pyproject.toml index 9a86ee621de6..70b12d6b12ba 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-media-type/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/aio/operations/_operations.py index b5b4cd142e0a..38d6fc1e5abc 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/aio/operations/_operations.py @@ -14,8 +14,8 @@ from corehttp.runtime import AsyncPipelineClient from corehttp.runtime.pipeline import PipelineResponse -from ... import models as _models2 -from .... import models as _models3 +from ... import models as _models2, types as _types_models2 +from .... import models as _models3, types as _types_models3 from ...._utils.model_base import Model as _Model from ...._utils.serialization import Deserializer, Serializer from ...._utils.utils import prepare_multipart_form_data @@ -34,7 +34,6 @@ build_form_data_with_wire_name_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -71,21 +70,24 @@ async def basic(self, body: _models3.MultiPartRequest, **kwargs: Any) -> None: """ @overload - async def basic(self, body: JSON, **kwargs: Any) -> None: + async def basic(self, body: _types_models3.MultiPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ - async def basic(self, body: Union[_models3.MultiPartRequest, JSON], **kwargs: Any) -> None: + async def basic( + self, body: Union[_models3.MultiPartRequest, _types_models3.MultiPartRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a MultiPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequest or JSON + :param body: Is one of the following types: MultiPartRequest Required. + :type body: ~payload.multipart.models.MultiPartRequest or + ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -142,21 +144,26 @@ async def with_wire_name(self, body: _models3.MultiPartRequestWithWireName, **kw """ @overload - async def with_wire_name(self, body: JSON, **kwargs: Any) -> None: + async def with_wire_name(self, body: _types_models3.MultiPartRequestWithWireName, **kwargs: Any) -> None: """Test content-type: multipart/form-data with wire names. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequestWithWireName :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_wire_name(self, body: Union[_models3.MultiPartRequestWithWireName, JSON], **kwargs: Any) -> None: + async def with_wire_name( + self, + body: Union[_models3.MultiPartRequestWithWireName, _types_models3.MultiPartRequestWithWireName], + **kwargs: Any + ) -> None: """Test content-type: multipart/form-data with wire names. - :param body: Is either a MultiPartRequestWithWireName type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequestWithWireName or JSON + :param body: Is one of the following types: MultiPartRequestWithWireName Required. + :type body: ~payload.multipart.models.MultiPartRequestWithWireName or + ~payload.multipart.types.MultiPartRequestWithWireName :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -213,21 +220,24 @@ async def optional_parts(self, body: _models3.MultiPartOptionalRequest, **kwargs """ @overload - async def optional_parts(self, body: JSON, **kwargs: Any) -> None: + async def optional_parts(self, body: _types_models3.MultiPartOptionalRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data with optional parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartOptionalRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ - async def optional_parts(self, body: Union[_models3.MultiPartOptionalRequest, JSON], **kwargs: Any) -> None: + async def optional_parts( + self, body: Union[_models3.MultiPartOptionalRequest, _types_models3.MultiPartOptionalRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data with optional parts. - :param body: Is either a MultiPartOptionalRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartOptionalRequest or JSON + :param body: Is one of the following types: MultiPartOptionalRequest Required. + :type body: ~payload.multipart.models.MultiPartOptionalRequest or + ~payload.multipart.types.MultiPartOptionalRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -284,21 +294,24 @@ async def file_array_and_basic(self, body: _models3.ComplexPartsRequest, **kwarg """ @overload - async def file_array_and_basic(self, body: JSON, **kwargs: Any) -> None: + async def file_array_and_basic(self, body: _types_models3.ComplexPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for mixed scenarios. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.ComplexPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ - async def file_array_and_basic(self, body: Union[_models3.ComplexPartsRequest, JSON], **kwargs: Any) -> None: + async def file_array_and_basic( + self, body: Union[_models3.ComplexPartsRequest, _types_models3.ComplexPartsRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data for mixed scenarios. - :param body: Is either a ComplexPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.ComplexPartsRequest or JSON + :param body: Is one of the following types: ComplexPartsRequest Required. + :type body: ~payload.multipart.models.ComplexPartsRequest or + ~payload.multipart.types.ComplexPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -355,21 +368,24 @@ async def json_part(self, body: _models3.JsonPartRequest, **kwargs: Any) -> None """ @overload - async def json_part(self, body: JSON, **kwargs: Any) -> None: + async def json_part(self, body: _types_models3.JsonPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains json part and binary part. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.JsonPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ - async def json_part(self, body: Union[_models3.JsonPartRequest, JSON], **kwargs: Any) -> None: + async def json_part( + self, body: Union[_models3.JsonPartRequest, _types_models3.JsonPartRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data for scenario contains json part and binary part. - :param body: Is either a JsonPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.JsonPartRequest or JSON + :param body: Is one of the following types: JsonPartRequest Required. + :type body: ~payload.multipart.models.JsonPartRequest or + ~payload.multipart.types.JsonPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -426,21 +442,24 @@ async def binary_array_parts(self, body: _models3.BinaryArrayPartsRequest, **kwa """ @overload - async def binary_array_parts(self, body: JSON, **kwargs: Any) -> None: + async def binary_array_parts(self, body: _types_models3.BinaryArrayPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.BinaryArrayPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ - async def binary_array_parts(self, body: Union[_models3.BinaryArrayPartsRequest, JSON], **kwargs: Any) -> None: + async def binary_array_parts( + self, body: Union[_models3.BinaryArrayPartsRequest, _types_models3.BinaryArrayPartsRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. - :param body: Is either a BinaryArrayPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.BinaryArrayPartsRequest or JSON + :param body: Is one of the following types: BinaryArrayPartsRequest Required. + :type body: ~payload.multipart.models.BinaryArrayPartsRequest or + ~payload.multipart.types.BinaryArrayPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -497,21 +516,24 @@ async def multi_binary_parts(self, body: _models3.MultiBinaryPartsRequest, **kwa """ @overload - async def multi_binary_parts(self, body: JSON, **kwargs: Any) -> None: + async def multi_binary_parts(self, body: _types_models3.MultiBinaryPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiBinaryPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ - async def multi_binary_parts(self, body: Union[_models3.MultiBinaryPartsRequest, JSON], **kwargs: Any) -> None: + async def multi_binary_parts( + self, body: Union[_models3.MultiBinaryPartsRequest, _types_models3.MultiBinaryPartsRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. - :param body: Is either a MultiBinaryPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiBinaryPartsRequest or JSON + :param body: Is one of the following types: MultiBinaryPartsRequest Required. + :type body: ~payload.multipart.models.MultiBinaryPartsRequest or + ~payload.multipart.types.MultiBinaryPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -568,23 +590,24 @@ async def check_file_name_and_content_type(self, body: _models3.MultiPartRequest """ @overload - async def check_file_name_and_content_type(self, body: JSON, **kwargs: Any) -> None: + async def check_file_name_and_content_type(self, body: _types_models3.MultiPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ async def check_file_name_and_content_type( - self, body: Union[_models3.MultiPartRequest, JSON], **kwargs: Any + self, body: Union[_models3.MultiPartRequest, _types_models3.MultiPartRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a MultiPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequest or JSON + :param body: Is one of the following types: MultiPartRequest Required. + :type body: ~payload.multipart.models.MultiPartRequest or + ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -641,21 +664,24 @@ async def anonymous_model(self, body: _models2.AnonymousModelRequest, **kwargs: """ @overload - async def anonymous_model(self, body: JSON, **kwargs: Any) -> None: + async def anonymous_model(self, body: _types_models2.AnonymousModelRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.formdata.types.AnonymousModelRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ - async def anonymous_model(self, body: Union[_models2.AnonymousModelRequest, JSON], **kwargs: Any) -> None: + async def anonymous_model( + self, body: Union[_models2.AnonymousModelRequest, _types_models2.AnonymousModelRequest], **kwargs: Any + ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a AnonymousModelRequest type or a JSON type. Required. - :type body: ~payload.multipart.formdata.models.AnonymousModelRequest or JSON + :param body: Is one of the following types: AnonymousModelRequest Required. + :type body: ~payload.multipart.formdata.models.AnonymousModelRequest or + ~payload.multipart.formdata.types.AnonymousModelRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/aio/operations/_operations.py index fa06202194cd..51fc2475c904 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/aio/operations/_operations.py @@ -14,7 +14,7 @@ from corehttp.runtime import AsyncPipelineClient from corehttp.runtime.pipeline import PipelineResponse -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ....._utils.model_base import Model as _Model from ....._utils.serialization import Deserializer, Serializer from ....._utils.utils import prepare_multipart_form_data @@ -25,7 +25,6 @@ build_form_data_file_upload_file_specific_content_type_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -61,24 +60,28 @@ async def upload_file_specific_content_type( """ @overload - async def upload_file_specific_content_type(self, body: JSON, **kwargs: Any) -> None: + async def upload_file_specific_content_type( + self, body: _types_models2.UploadFileSpecificContentTypeRequest, **kwargs: Any + ) -> None: """upload_file_specific_content_type. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.formdata.file.types.UploadFileSpecificContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ async def upload_file_specific_content_type( - self, body: Union[_models2.UploadFileSpecificContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[_models2.UploadFileSpecificContentTypeRequest, _types_models2.UploadFileSpecificContentTypeRequest], + **kwargs: Any ) -> None: """upload_file_specific_content_type. - :param body: Is either a UploadFileSpecificContentTypeRequest type or a JSON type. Required. + :param body: Is one of the following types: UploadFileSpecificContentTypeRequest Required. :type body: ~payload.multipart.formdata.file.models.UploadFileSpecificContentTypeRequest or - JSON + ~payload.multipart.formdata.file.types.UploadFileSpecificContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -137,23 +140,28 @@ async def upload_file_required_filename( """ @overload - async def upload_file_required_filename(self, body: JSON, **kwargs: Any) -> None: + async def upload_file_required_filename( + self, body: _types_models2.UploadFileRequiredFilenameRequest, **kwargs: Any + ) -> None: """upload_file_required_filename. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.formdata.file.types.UploadFileRequiredFilenameRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ async def upload_file_required_filename( - self, body: Union[_models2.UploadFileRequiredFilenameRequest, JSON], **kwargs: Any + self, + body: Union[_models2.UploadFileRequiredFilenameRequest, _types_models2.UploadFileRequiredFilenameRequest], + **kwargs: Any ) -> None: """upload_file_required_filename. - :param body: Is either a UploadFileRequiredFilenameRequest type or a JSON type. Required. - :type body: ~payload.multipart.formdata.file.models.UploadFileRequiredFilenameRequest or JSON + :param body: Is one of the following types: UploadFileRequiredFilenameRequest Required. + :type body: ~payload.multipart.formdata.file.models.UploadFileRequiredFilenameRequest or + ~payload.multipart.formdata.file.types.UploadFileRequiredFilenameRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -210,21 +218,24 @@ async def upload_file_array(self, body: _models2.UploadFileArrayRequest, **kwarg """ @overload - async def upload_file_array(self, body: JSON, **kwargs: Any) -> None: + async def upload_file_array(self, body: _types_models2.UploadFileArrayRequest, **kwargs: Any) -> None: """upload_file_array. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.formdata.file.types.UploadFileArrayRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ - async def upload_file_array(self, body: Union[_models2.UploadFileArrayRequest, JSON], **kwargs: Any) -> None: + async def upload_file_array( + self, body: Union[_models2.UploadFileArrayRequest, _types_models2.UploadFileArrayRequest], **kwargs: Any + ) -> None: """upload_file_array. - :param body: Is either a UploadFileArrayRequest type or a JSON type. Required. - :type body: ~payload.multipart.formdata.file.models.UploadFileArrayRequest or JSON + :param body: Is one of the following types: UploadFileArrayRequest Required. + :type body: ~payload.multipart.formdata.file.models.UploadFileArrayRequest or + ~payload.multipart.formdata.file.types.UploadFileArrayRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/aio/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/aio/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/models/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/models/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/operations/_operations.py index 3b0ebc376544..594e7023a3c4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/operations/_operations.py @@ -15,13 +15,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from ...._configuration import MultiPartClientConfiguration from ...._utils.model_base import Model as _Model from ...._utils.serialization import Deserializer, Serializer from ...._utils.utils import prepare_multipart_form_data -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -91,24 +90,28 @@ def upload_file_specific_content_type( """ @overload - def upload_file_specific_content_type(self, body: JSON, **kwargs: Any) -> None: + def upload_file_specific_content_type( + self, body: _types_models1.UploadFileSpecificContentTypeRequest, **kwargs: Any + ) -> None: """upload_file_specific_content_type. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.formdata.file.types.UploadFileSpecificContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def upload_file_specific_content_type( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.UploadFileSpecificContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[_models1.UploadFileSpecificContentTypeRequest, _types_models1.UploadFileSpecificContentTypeRequest], + **kwargs: Any, ) -> None: """upload_file_specific_content_type. - :param body: Is either a UploadFileSpecificContentTypeRequest type or a JSON type. Required. + :param body: Is one of the following types: UploadFileSpecificContentTypeRequest Required. :type body: ~payload.multipart.formdata.file.models.UploadFileSpecificContentTypeRequest or - JSON + ~payload.multipart.formdata.file.types.UploadFileSpecificContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -165,23 +168,28 @@ def upload_file_required_filename(self, body: _models1.UploadFileRequiredFilenam """ @overload - def upload_file_required_filename(self, body: JSON, **kwargs: Any) -> None: + def upload_file_required_filename( + self, body: _types_models1.UploadFileRequiredFilenameRequest, **kwargs: Any + ) -> None: """upload_file_required_filename. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.formdata.file.types.UploadFileRequiredFilenameRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def upload_file_required_filename( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.UploadFileRequiredFilenameRequest, JSON], **kwargs: Any + self, + body: Union[_models1.UploadFileRequiredFilenameRequest, _types_models1.UploadFileRequiredFilenameRequest], + **kwargs: Any, ) -> None: """upload_file_required_filename. - :param body: Is either a UploadFileRequiredFilenameRequest type or a JSON type. Required. - :type body: ~payload.multipart.formdata.file.models.UploadFileRequiredFilenameRequest or JSON + :param body: Is one of the following types: UploadFileRequiredFilenameRequest Required. + :type body: ~payload.multipart.formdata.file.models.UploadFileRequiredFilenameRequest or + ~payload.multipart.formdata.file.types.UploadFileRequiredFilenameRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -238,23 +246,24 @@ def upload_file_array(self, body: _models1.UploadFileArrayRequest, **kwargs: Any """ @overload - def upload_file_array(self, body: JSON, **kwargs: Any) -> None: + def upload_file_array(self, body: _types_models1.UploadFileArrayRequest, **kwargs: Any) -> None: """upload_file_array. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.formdata.file.types.UploadFileArrayRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def upload_file_array( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.UploadFileArrayRequest, JSON], **kwargs: Any + self, body: Union[_models1.UploadFileArrayRequest, _types_models1.UploadFileArrayRequest], **kwargs: Any ) -> None: """upload_file_array. - :param body: Is either a UploadFileArrayRequest type or a JSON type. Required. - :type body: ~payload.multipart.formdata.file.models.UploadFileArrayRequest or JSON + :param body: Is one of the following types: UploadFileArrayRequest Required. + :type body: ~payload.multipart.formdata.file.models.UploadFileArrayRequest or + ~payload.multipart.formdata.file.types.UploadFileArrayRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/types.py index a5c98f2da3e1..af26844e80e6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/file/types.py @@ -9,7 +9,7 @@ class UploadFileArrayRequest(TypedDict, total=False): """UploadFileArrayRequest. :ivar files: Required. - :vartype files: list[~payload.multipart._utils.utils.FileType] + :vartype files: list[FileType] """ files: Required[list[FileType]] @@ -20,7 +20,7 @@ class UploadFileRequiredFilenameRequest(TypedDict, total=False): """UploadFileRequiredFilenameRequest. :ivar file: Required. - :vartype file: ~payload.multipart._utils.utils.FileType + :vartype file: FileType """ file: Required[FileType] @@ -31,7 +31,7 @@ class UploadFileSpecificContentTypeRequest(TypedDict, total=False): """UploadFileSpecificContentTypeRequest. :ivar file: Required. - :vartype file: ~payload.multipart._utils.utils.FileType + :vartype file: FileType """ file: Required[FileType] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/aio/operations/_operations.py index 88e0e6c4d724..1236e0c622bf 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/aio/operations/_operations.py @@ -14,7 +14,7 @@ from corehttp.runtime import AsyncPipelineClient from corehttp.runtime.pipeline import PipelineResponse -from ..... import models as _models4 +from ..... import models as _models4, types as _types_models4 from ....._utils.model_base import Model as _Model from ....._utils.serialization import Deserializer, Serializer from ....._utils.utils import prepare_multipart_form_data @@ -23,7 +23,6 @@ from ...nonstring.aio.operations._operations import FormDataHttpPartsNonStringOperations from ...operations._operations import build_form_data_http_parts_json_array_and_file_array_request -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -64,23 +63,26 @@ async def json_array_and_file_array(self, body: _models4.ComplexHttpPartsModelRe """ @overload - async def json_array_and_file_array(self, body: JSON, **kwargs: Any) -> None: + async def json_array_and_file_array(self, body: _types_models4.ComplexHttpPartsModelRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for mixed scenarios. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.ComplexHttpPartsModelRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ async def json_array_and_file_array( - self, body: Union[_models4.ComplexHttpPartsModelRequest, JSON], **kwargs: Any + self, + body: Union[_models4.ComplexHttpPartsModelRequest, _types_models4.ComplexHttpPartsModelRequest], + **kwargs: Any ) -> None: """Test content-type: multipart/form-data for mixed scenarios. - :param body: Is either a ComplexHttpPartsModelRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.ComplexHttpPartsModelRequest or JSON + :param body: Is one of the following types: ComplexHttpPartsModelRequest Required. + :type body: ~payload.multipart.models.ComplexHttpPartsModelRequest or + ~payload.multipart.types.ComplexHttpPartsModelRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/aio/operations/_operations.py index 8126e20f1aa6..94e9e09681dd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/aio/operations/_operations.py @@ -14,7 +14,7 @@ from corehttp.runtime import AsyncPipelineClient from corehttp.runtime.pipeline import PipelineResponse -from ...... import models as _models5 +from ...... import models as _models5, types as _types_models5 from ......_utils.model_base import Model as _Model from ......_utils.serialization import Deserializer, Serializer from ......_utils.utils import prepare_multipart_form_data @@ -25,7 +25,6 @@ build_form_data_http_parts_content_type_required_content_type_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -61,24 +60,32 @@ async def image_jpeg_content_type( """ @overload - async def image_jpeg_content_type(self, body: JSON, **kwargs: Any) -> None: + async def image_jpeg_content_type( + self, body: _types_models5.FileWithHttpPartSpecificContentTypeRequest, **kwargs: Any + ) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartSpecificContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ async def image_jpeg_content_type( - self, body: Union[_models5.FileWithHttpPartSpecificContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models5.FileWithHttpPartSpecificContentTypeRequest, + _types_models5.FileWithHttpPartSpecificContentTypeRequest, + ], + **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a FileWithHttpPartSpecificContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartSpecificContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartSpecificContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartSpecificContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartSpecificContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -137,24 +144,32 @@ async def required_content_type( """ @overload - async def required_content_type(self, body: JSON, **kwargs: Any) -> None: + async def required_content_type( + self, body: _types_models5.FileWithHttpPartRequiredContentTypeRequest, **kwargs: Any + ) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartRequiredContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ async def required_content_type( - self, body: Union[_models5.FileWithHttpPartRequiredContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models5.FileWithHttpPartRequiredContentTypeRequest, + _types_models5.FileWithHttpPartRequiredContentTypeRequest, + ], + **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a FileWithHttpPartRequiredContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartRequiredContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartRequiredContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartRequiredContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartRequiredContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -213,24 +228,32 @@ async def optional_content_type( """ @overload - async def optional_content_type(self, body: JSON, **kwargs: Any) -> None: + async def optional_content_type( + self, body: _types_models5.FileWithHttpPartOptionalContentTypeRequest, **kwargs: Any + ) -> None: """Test content-type: multipart/form-data for optional content type. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartOptionalContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ async def optional_content_type( - self, body: Union[_models5.FileWithHttpPartOptionalContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models5.FileWithHttpPartOptionalContentTypeRequest, + _types_models5.FileWithHttpPartOptionalContentTypeRequest, + ], + **kwargs: Any ) -> None: """Test content-type: multipart/form-data for optional content type. - :param body: Is either a FileWithHttpPartOptionalContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartOptionalContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartOptionalContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartOptionalContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartOptionalContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/operations/_operations.py index ce1e8d8fdde5..9b27ab493ef4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/operations/_operations.py @@ -15,13 +15,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ..... import models as _models4 +from ..... import models as _models4, types as _types_models4 from ....._configuration import MultiPartClientConfiguration from ....._utils.model_base import Model as _Model from ....._utils.serialization import Deserializer, Serializer from ....._utils.utils import prepare_multipart_form_data -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -91,24 +90,32 @@ def image_jpeg_content_type(self, body: _models4.FileWithHttpPartSpecificContent """ @overload - def image_jpeg_content_type(self, body: JSON, **kwargs: Any) -> None: + def image_jpeg_content_type( + self, body: _types_models4.FileWithHttpPartSpecificContentTypeRequest, **kwargs: Any + ) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartSpecificContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def image_jpeg_content_type( # pylint: disable=inconsistent-return-statements - self, body: Union[_models4.FileWithHttpPartSpecificContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models4.FileWithHttpPartSpecificContentTypeRequest, + _types_models4.FileWithHttpPartSpecificContentTypeRequest, + ], + **kwargs: Any, ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a FileWithHttpPartSpecificContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartSpecificContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartSpecificContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartSpecificContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartSpecificContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -165,24 +172,32 @@ def required_content_type(self, body: _models4.FileWithHttpPartRequiredContentTy """ @overload - def required_content_type(self, body: JSON, **kwargs: Any) -> None: + def required_content_type( + self, body: _types_models4.FileWithHttpPartRequiredContentTypeRequest, **kwargs: Any + ) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartRequiredContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def required_content_type( # pylint: disable=inconsistent-return-statements - self, body: Union[_models4.FileWithHttpPartRequiredContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models4.FileWithHttpPartRequiredContentTypeRequest, + _types_models4.FileWithHttpPartRequiredContentTypeRequest, + ], + **kwargs: Any, ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a FileWithHttpPartRequiredContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartRequiredContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartRequiredContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartRequiredContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartRequiredContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -239,24 +254,32 @@ def optional_content_type(self, body: _models4.FileWithHttpPartOptionalContentTy """ @overload - def optional_content_type(self, body: JSON, **kwargs: Any) -> None: + def optional_content_type( + self, body: _types_models4.FileWithHttpPartOptionalContentTypeRequest, **kwargs: Any + ) -> None: """Test content-type: multipart/form-data for optional content type. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.FileWithHttpPartOptionalContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def optional_content_type( # pylint: disable=inconsistent-return-statements - self, body: Union[_models4.FileWithHttpPartOptionalContentTypeRequest, JSON], **kwargs: Any + self, + body: Union[ + _models4.FileWithHttpPartOptionalContentTypeRequest, + _types_models4.FileWithHttpPartOptionalContentTypeRequest, + ], + **kwargs: Any, ) -> None: """Test content-type: multipart/form-data for optional content type. - :param body: Is either a FileWithHttpPartOptionalContentTypeRequest type or a JSON type. + :param body: Is one of the following types: FileWithHttpPartOptionalContentTypeRequest Required. - :type body: ~payload.multipart.models.FileWithHttpPartOptionalContentTypeRequest or JSON + :type body: ~payload.multipart.models.FileWithHttpPartOptionalContentTypeRequest or + ~payload.multipart.types.FileWithHttpPartOptionalContentTypeRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/contenttype/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/aio/operations/_operations.py index 2a8c1f21f15b..cbbe9686b4f8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/aio/operations/_operations.py @@ -14,14 +14,13 @@ from corehttp.runtime import AsyncPipelineClient from corehttp.runtime.pipeline import PipelineResponse -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ......_utils.model_base import Model as _Model from ......_utils.serialization import Deserializer, Serializer from ......_utils.utils import prepare_multipart_form_data from ......aio._configuration import MultiPartClientConfiguration from ...operations._operations import build_form_data_http_parts_non_string_float_request -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -55,21 +54,22 @@ async def float(self, body: _models2.FloatRequest, **kwargs: Any) -> None: """ @overload - async def float(self, body: JSON, **kwargs: Any) -> None: + async def float(self, body: _types_models2.FloatRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for non string. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.formdata.httpparts.nonstring.types.FloatRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ - async def float(self, body: Union[_models2.FloatRequest, JSON], **kwargs: Any) -> None: + async def float(self, body: Union[_models2.FloatRequest, _types_models2.FloatRequest], **kwargs: Any) -> None: """Test content-type: multipart/form-data for non string. - :param body: Is either a FloatRequest type or a JSON type. Required. - :type body: ~payload.multipart.formdata.httpparts.nonstring.models.FloatRequest or JSON + :param body: Is one of the following types: FloatRequest Required. + :type body: ~payload.multipart.formdata.httpparts.nonstring.models.FloatRequest or + ~payload.multipart.formdata.httpparts.nonstring.types.FloatRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/operations/_operations.py index df81cc46262b..981e3d46cfa0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/operations/_operations.py @@ -15,13 +15,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from ....._configuration import MultiPartClientConfiguration from ....._utils.model_base import Model as _Model from ....._utils.serialization import Deserializer, Serializer from ....._utils.utils import prepare_multipart_form_data -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -67,23 +66,24 @@ def float(self, body: _models1.FloatRequest, **kwargs: Any) -> None: """ @overload - def float(self, body: JSON, **kwargs: Any) -> None: + def float(self, body: _types_models1.FloatRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for non string. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.formdata.httpparts.nonstring.types.FloatRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def float( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.FloatRequest, JSON], **kwargs: Any + self, body: Union[_models1.FloatRequest, _types_models1.FloatRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for non string. - :param body: Is either a FloatRequest type or a JSON type. Required. - :type body: ~payload.multipart.formdata.httpparts.nonstring.models.FloatRequest or JSON + :param body: Is one of the following types: FloatRequest Required. + :type body: ~payload.multipart.formdata.httpparts.nonstring.models.FloatRequest or + ~payload.multipart.formdata.httpparts.nonstring.types.FloatRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/nonstring/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/operations/_operations.py index 375fa67116a8..ef7011b676be 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/operations/_operations.py @@ -15,7 +15,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .... import models as _models3 +from .... import models as _models3, types as _types_models3 from ...._configuration import MultiPartClientConfiguration from ...._utils.model_base import Model as _Model from ...._utils.serialization import Deserializer, Serializer @@ -23,7 +23,6 @@ from ..contenttype.operations._operations import FormDataHttpPartsContentTypeOperations from ..nonstring.operations._operations import FormDataHttpPartsNonStringOperations -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -78,23 +77,26 @@ def json_array_and_file_array(self, body: _models3.ComplexHttpPartsModelRequest, """ @overload - def json_array_and_file_array(self, body: JSON, **kwargs: Any) -> None: + def json_array_and_file_array(self, body: _types_models3.ComplexHttpPartsModelRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for mixed scenarios. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.ComplexHttpPartsModelRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def json_array_and_file_array( # pylint: disable=inconsistent-return-statements - self, body: Union[_models3.ComplexHttpPartsModelRequest, JSON], **kwargs: Any + self, + body: Union[_models3.ComplexHttpPartsModelRequest, _types_models3.ComplexHttpPartsModelRequest], + **kwargs: Any, ) -> None: """Test content-type: multipart/form-data for mixed scenarios. - :param body: Is either a ComplexHttpPartsModelRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.ComplexHttpPartsModelRequest or JSON + :param body: Is one of the following types: ComplexHttpPartsModelRequest Required. + :type body: ~payload.multipart.models.ComplexHttpPartsModelRequest or + ~payload.multipart.types.ComplexHttpPartsModelRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/httpparts/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/operations/_operations.py index b892bbb2690d..653523cd5d29 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/operations/_operations.py @@ -15,8 +15,8 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 -from ... import models as _models2 +from .. import models as _models1, types as _types_models1 +from ... import models as _models2, types as _types_models2 from ..._configuration import MultiPartClientConfiguration from ..._utils.model_base import Model as _Model from ..._utils.serialization import Deserializer, Serializer @@ -24,7 +24,6 @@ from ..file.operations._operations import FormDataFileOperations from ..httpparts.operations._operations import FormDataHttpPartsOperations -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -147,23 +146,24 @@ def basic(self, body: _models2.MultiPartRequest, **kwargs: Any) -> None: """ @overload - def basic(self, body: JSON, **kwargs: Any) -> None: + def basic(self, body: _types_models2.MultiPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def basic( # pylint: disable=inconsistent-return-statements - self, body: Union[_models2.MultiPartRequest, JSON], **kwargs: Any + self, body: Union[_models2.MultiPartRequest, _types_models2.MultiPartRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a MultiPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequest or JSON + :param body: Is one of the following types: MultiPartRequest Required. + :type body: ~payload.multipart.models.MultiPartRequest or + ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -220,23 +220,26 @@ def with_wire_name(self, body: _models2.MultiPartRequestWithWireName, **kwargs: """ @overload - def with_wire_name(self, body: JSON, **kwargs: Any) -> None: + def with_wire_name(self, body: _types_models2.MultiPartRequestWithWireName, **kwargs: Any) -> None: """Test content-type: multipart/form-data with wire names. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequestWithWireName :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def with_wire_name( # pylint: disable=inconsistent-return-statements - self, body: Union[_models2.MultiPartRequestWithWireName, JSON], **kwargs: Any + self, + body: Union[_models2.MultiPartRequestWithWireName, _types_models2.MultiPartRequestWithWireName], + **kwargs: Any, ) -> None: """Test content-type: multipart/form-data with wire names. - :param body: Is either a MultiPartRequestWithWireName type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequestWithWireName or JSON + :param body: Is one of the following types: MultiPartRequestWithWireName Required. + :type body: ~payload.multipart.models.MultiPartRequestWithWireName or + ~payload.multipart.types.MultiPartRequestWithWireName :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -293,23 +296,24 @@ def optional_parts(self, body: _models2.MultiPartOptionalRequest, **kwargs: Any) """ @overload - def optional_parts(self, body: JSON, **kwargs: Any) -> None: + def optional_parts(self, body: _types_models2.MultiPartOptionalRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data with optional parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartOptionalRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def optional_parts( # pylint: disable=inconsistent-return-statements - self, body: Union[_models2.MultiPartOptionalRequest, JSON], **kwargs: Any + self, body: Union[_models2.MultiPartOptionalRequest, _types_models2.MultiPartOptionalRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data with optional parts. - :param body: Is either a MultiPartOptionalRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartOptionalRequest or JSON + :param body: Is one of the following types: MultiPartOptionalRequest Required. + :type body: ~payload.multipart.models.MultiPartOptionalRequest or + ~payload.multipart.types.MultiPartOptionalRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -366,23 +370,24 @@ def file_array_and_basic(self, body: _models2.ComplexPartsRequest, **kwargs: Any """ @overload - def file_array_and_basic(self, body: JSON, **kwargs: Any) -> None: + def file_array_and_basic(self, body: _types_models2.ComplexPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for mixed scenarios. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.ComplexPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def file_array_and_basic( # pylint: disable=inconsistent-return-statements - self, body: Union[_models2.ComplexPartsRequest, JSON], **kwargs: Any + self, body: Union[_models2.ComplexPartsRequest, _types_models2.ComplexPartsRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for mixed scenarios. - :param body: Is either a ComplexPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.ComplexPartsRequest or JSON + :param body: Is one of the following types: ComplexPartsRequest Required. + :type body: ~payload.multipart.models.ComplexPartsRequest or + ~payload.multipart.types.ComplexPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -439,23 +444,24 @@ def json_part(self, body: _models2.JsonPartRequest, **kwargs: Any) -> None: """ @overload - def json_part(self, body: JSON, **kwargs: Any) -> None: + def json_part(self, body: _types_models2.JsonPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains json part and binary part. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.JsonPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def json_part( # pylint: disable=inconsistent-return-statements - self, body: Union[_models2.JsonPartRequest, JSON], **kwargs: Any + self, body: Union[_models2.JsonPartRequest, _types_models2.JsonPartRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for scenario contains json part and binary part. - :param body: Is either a JsonPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.JsonPartRequest or JSON + :param body: Is one of the following types: JsonPartRequest Required. + :type body: ~payload.multipart.models.JsonPartRequest or + ~payload.multipart.types.JsonPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -512,23 +518,24 @@ def binary_array_parts(self, body: _models2.BinaryArrayPartsRequest, **kwargs: A """ @overload - def binary_array_parts(self, body: JSON, **kwargs: Any) -> None: + def binary_array_parts(self, body: _types_models2.BinaryArrayPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.BinaryArrayPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def binary_array_parts( # pylint: disable=inconsistent-return-statements - self, body: Union[_models2.BinaryArrayPartsRequest, JSON], **kwargs: Any + self, body: Union[_models2.BinaryArrayPartsRequest, _types_models2.BinaryArrayPartsRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. - :param body: Is either a BinaryArrayPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.BinaryArrayPartsRequest or JSON + :param body: Is one of the following types: BinaryArrayPartsRequest Required. + :type body: ~payload.multipart.models.BinaryArrayPartsRequest or + ~payload.multipart.types.BinaryArrayPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -585,23 +592,24 @@ def multi_binary_parts(self, body: _models2.MultiBinaryPartsRequest, **kwargs: A """ @overload - def multi_binary_parts(self, body: JSON, **kwargs: Any) -> None: + def multi_binary_parts(self, body: _types_models2.MultiBinaryPartsRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiBinaryPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def multi_binary_parts( # pylint: disable=inconsistent-return-statements - self, body: Union[_models2.MultiBinaryPartsRequest, JSON], **kwargs: Any + self, body: Union[_models2.MultiBinaryPartsRequest, _types_models2.MultiBinaryPartsRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data for scenario contains multi binary parts. - :param body: Is either a MultiBinaryPartsRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiBinaryPartsRequest or JSON + :param body: Is one of the following types: MultiBinaryPartsRequest Required. + :type body: ~payload.multipart.models.MultiBinaryPartsRequest or + ~payload.multipart.types.MultiBinaryPartsRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -658,23 +666,24 @@ def check_file_name_and_content_type(self, body: _models2.MultiPartRequest, **kw """ @overload - def check_file_name_and_content_type(self, body: JSON, **kwargs: Any) -> None: + def check_file_name_and_content_type(self, body: _types_models2.MultiPartRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def check_file_name_and_content_type( # pylint: disable=inconsistent-return-statements - self, body: Union[_models2.MultiPartRequest, JSON], **kwargs: Any + self, body: Union[_models2.MultiPartRequest, _types_models2.MultiPartRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a MultiPartRequest type or a JSON type. Required. - :type body: ~payload.multipart.models.MultiPartRequest or JSON + :param body: Is one of the following types: MultiPartRequest Required. + :type body: ~payload.multipart.models.MultiPartRequest or + ~payload.multipart.types.MultiPartRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -731,23 +740,24 @@ def anonymous_model(self, body: _models1.AnonymousModelRequest, **kwargs: Any) - """ @overload - def anonymous_model(self, body: JSON, **kwargs: Any) -> None: + def anonymous_model(self, body: _types_models1.AnonymousModelRequest, **kwargs: Any) -> None: """Test content-type: multipart/form-data. :param body: Required. - :type body: JSON + :type body: ~payload.multipart.formdata.types.AnonymousModelRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: """ def anonymous_model( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.AnonymousModelRequest, JSON], **kwargs: Any + self, body: Union[_models1.AnonymousModelRequest, _types_models1.AnonymousModelRequest], **kwargs: Any ) -> None: """Test content-type: multipart/form-data. - :param body: Is either a AnonymousModelRequest type or a JSON type. Required. - :type body: ~payload.multipart.formdata.models.AnonymousModelRequest or JSON + :param body: Is one of the following types: AnonymousModelRequest Required. + :type body: ~payload.multipart.formdata.models.AnonymousModelRequest or + ~payload.multipart.formdata.types.AnonymousModelRequest :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/types.py index ac13bd6283f6..f6c74c211b11 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/formdata/types.py @@ -9,7 +9,7 @@ class AnonymousModelRequest(TypedDict, total=False): """AnonymousModelRequest. :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ profileImage: Required[FileType] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/types.py index 80d8dddf253d..bba33cb43b06 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/payload/multipart/types.py @@ -22,7 +22,7 @@ class BinaryArrayPartsRequest(TypedDict, total=False): :ivar id: Required. :vartype id: str :ivar pictures: Required. - :vartype pictures: list[~payload.multipart._utils.utils.FileType] + :vartype pictures: list[FileType] """ id: Required[str] @@ -37,13 +37,13 @@ class ComplexHttpPartsModelRequest(TypedDict, total=False): :ivar id: Required. :vartype id: str :ivar address: Required. - :vartype address: ~payload.multipart.models.Address + :vartype address: "Address" :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType :ivar previous_addresses: Required. - :vartype previous_addresses: list[~payload.multipart.models.Address] + :vartype previous_addresses: list["Address"] :ivar pictures: Required. - :vartype pictures: list[~payload.multipart._utils.utils.FileType] + :vartype pictures: list[FileType] """ id: Required[str] @@ -64,11 +64,11 @@ class ComplexPartsRequest(TypedDict, total=False): :ivar id: Required. :vartype id: str :ivar address: Required. - :vartype address: ~payload.multipart.models.Address + :vartype address: "Address" :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType :ivar pictures: Required. - :vartype pictures: list[~payload.multipart._utils.utils.FileType] + :vartype pictures: list[FileType] """ id: Required[str] @@ -85,7 +85,7 @@ class FileWithHttpPartOptionalContentTypeRequest(TypedDict, total=False): # pyl """FileWithHttpPartOptionalContentTypeRequest. :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ profileImage: Required[FileType] @@ -96,7 +96,7 @@ class FileWithHttpPartRequiredContentTypeRequest(TypedDict, total=False): # pyl """FileWithHttpPartRequiredContentTypeRequest. :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ profileImage: Required[FileType] @@ -107,7 +107,7 @@ class FileWithHttpPartSpecificContentTypeRequest(TypedDict, total=False): # pyl """FileWithHttpPartSpecificContentTypeRequest. :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ profileImage: Required[FileType] @@ -118,9 +118,9 @@ class JsonPartRequest(TypedDict, total=False): """JsonPartRequest. :ivar address: Required. - :vartype address: ~payload.multipart.models.Address + :vartype address: "Address" :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ address: Required["Address"] @@ -133,9 +133,9 @@ class MultiBinaryPartsRequest(TypedDict, total=False): """MultiBinaryPartsRequest. :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType :ivar picture: - :vartype picture: ~payload.multipart._utils.utils.FileType + :vartype picture: FileType """ profileImage: Required[FileType] @@ -149,7 +149,7 @@ class MultiPartOptionalRequest(TypedDict, total=False): :ivar id: :vartype id: str :ivar profile_image: - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ id: str @@ -162,7 +162,7 @@ class MultiPartRequest(TypedDict, total=False): :ivar id: Required. :vartype id: str :ivar profile_image: Required. - :vartype profile_image: ~payload.multipart._utils.utils.FileType + :vartype profile_image: FileType """ id: Required[str] @@ -177,7 +177,7 @@ class MultiPartRequestWithWireName(TypedDict, total=False): :ivar identifier: Required. :vartype identifier: str :ivar image: Required. - :vartype image: ~payload.multipart._utils.utils.FileType + :vartype image: FileType """ id: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/pyproject.toml index 64dc4754a3c6..1387b20ed7a5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-multipart/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_operations/_operations.py deleted file mode 100644 index f6d38edf6dee..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_operations/_operations.py +++ /dev/null @@ -1,115 +0,0 @@ -# coding=utf-8 -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from corehttp.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from corehttp.paging import ItemPaged -from corehttp.rest import HttpRequest, HttpResponse -from corehttp.runtime import PipelineClient -from corehttp.runtime.pipeline import PipelineResponse -from corehttp.utils import case_insensitive_dict - -from .. import models as _models1 -from .._configuration import PageableClientConfiguration -from .._utils.model_base import _deserialize -from .._utils.serialization import Serializer -from .._utils.utils import ClientMixinABC - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_pageable_list_without_continuation_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/payload/pageable/simple" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -class _PageableClientOperationsMixin( - ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], PageableClientConfiguration] -): - - def list_without_continuation(self, **kwargs: Any) -> ItemPaged["_models1.Pet"]: - """list_without_continuation. - - :return: An iterator like instance of Pet - :rtype: ~corehttp.paging.ItemPaged[~payload.pageable.models.Pet] - :raises ~corehttp.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models1.Pet]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_pageable_list_without_continuation_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - _request = HttpRequest("GET", next_link) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models1.Pet], deserialized.get("pets", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return ItemPaged(get_next, extract_data) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_operations/_operations.py deleted file mode 100644 index f1f9632422ce..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_operations/_operations.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding=utf-8 -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from corehttp.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from corehttp.paging import AsyncItemPaged, AsyncList -from corehttp.rest import AsyncHttpResponse, HttpRequest -from corehttp.runtime import AsyncPipelineClient -from corehttp.runtime.pipeline import PipelineResponse - -from ... import models as _models2 -from ..._operations._operations import build_pageable_list_without_continuation_request -from ..._utils.model_base import _deserialize -from ..._utils.utils import ClientMixinABC -from .._configuration import PageableClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class _PageableClientOperationsMixin( - ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], PageableClientConfiguration] -): - - def list_without_continuation(self, **kwargs: Any) -> AsyncItemPaged["_models2.Pet"]: - """list_without_continuation. - - :return: An iterator like instance of Pet - :rtype: ~corehttp.paging.AsyncItemPaged[~payload.pageable.models.Pet] - :raises ~corehttp.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models2.Pet]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_pageable_list_without_continuation_request( - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - _request = HttpRequest("GET", next_link) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(list[_models2.Pet], deserialized.get("pets", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client.pipeline.run( # type: ignore - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/pagesize/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/pagesize/aio/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/pagesize/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/pagesize/aio/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/pagesize/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/pagesize/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/pagesize/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/pagesize/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_operations.py index ca84347d5eba..738302f6d0ac 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_operations.py @@ -18,14 +18,13 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ..... import models as _models4 from ....._utils.model_base import SdkJSONEncoder, _deserialize from ....._utils.serialization import Deserializer, Serializer from .....aio._configuration import PageableClientConfiguration from ...operations._operations import build_server_driven_pagination_alternate_initial_verb_post_request -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -65,12 +64,12 @@ def post( @overload def post( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types_models2.Filter, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncItemPaged["_models4.Pet"]: """post. :param body: Required. - :type body: JSON + :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.types.Filter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -95,12 +94,14 @@ def post( :raises ~corehttp.exceptions.HttpResponseError: """ - def post(self, body: Union[_models2.Filter, JSON, IO[bytes]], **kwargs: Any) -> AsyncItemPaged["_models4.Pet"]: + def post( + self, body: Union[_models2.Filter, _types_models2.Filter, IO[bytes]], **kwargs: Any + ) -> AsyncItemPaged["_models4.Pet"]: """post. - :param body: Is one of the following types: Filter, JSON, IO[bytes] Required. - :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.models.Filter or JSON - or IO[bytes] + :param body: Is either a Filter type or a IO[bytes] type. Required. + :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.models.Filter or + ~payload.pageable.serverdrivenpagination.alternateinitialverb.types.Filter or IO[bytes] :return: An iterator like instance of Pet :rtype: ~corehttp.paging.AsyncItemPaged[~payload.pageable.models.Pet] :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/aio/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/models/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/models/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_operations.py index 13e06bde7ce8..d499dca2e77e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_operations.py @@ -18,13 +18,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from .... import models as _models3 from ...._configuration import PageableClientConfiguration from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -85,11 +84,13 @@ def post( """ @overload - def post(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> ItemPaged["_models3.Pet"]: + def post( + self, body: _types_models1.Filter, *, content_type: str = "application/json", **kwargs: Any + ) -> ItemPaged["_models3.Pet"]: """post. :param body: Required. - :type body: JSON + :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.types.Filter :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -114,12 +115,14 @@ def post( :raises ~corehttp.exceptions.HttpResponseError: """ - def post(self, body: Union[_models1.Filter, JSON, IO[bytes]], **kwargs: Any) -> ItemPaged["_models3.Pet"]: + def post( + self, body: Union[_models1.Filter, _types_models1.Filter, IO[bytes]], **kwargs: Any + ) -> ItemPaged["_models3.Pet"]: """post. - :param body: Is one of the following types: Filter, JSON, IO[bytes] Required. - :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.models.Filter or JSON - or IO[bytes] + :param body: Is either a Filter type or a IO[bytes] type. Required. + :type body: ~payload.pageable.serverdrivenpagination.alternateinitialverb.models.Filter or + ~payload.pageable.serverdrivenpagination.alternateinitialverb.types.Filter or IO[bytes] :return: An iterator like instance of Pet :rtype: ~corehttp.paging.ItemPaged[~payload.pageable.models.Pet] :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/alternateinitialverb/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/types.py deleted file mode 100644 index a13b29e1db4b..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/continuationtoken/types.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 - -from typing import TYPE_CHECKING -from typing_extensions import Required, TypedDict - -if TYPE_CHECKING: - from ...types import Pet - - -class RequestHeaderNestedResponseBodyResponseNestedItems(TypedDict, total=False): # pylint: disable=name-too-long - """RequestHeaderNestedResponseBodyResponseNestedItems. - - :ivar pets: Required. - :vartype pets: list[~payload.pageable.models.Pet] - """ - - pets: Required[list["Pet"]] - """Required.""" - - -class RequestHeaderNestedResponseBodyResponseNestedNext(TypedDict, total=False): # pylint: disable=name-too-long - """RequestHeaderNestedResponseBodyResponseNestedNext. - - :ivar next_token: - :vartype next_token: str - """ - - nextToken: str - - -class RequestQueryNestedResponseBodyResponseNestedItems(TypedDict, total=False): # pylint: disable=name-too-long - """RequestQueryNestedResponseBodyResponseNestedItems. - - :ivar pets: Required. - :vartype pets: list[~payload.pageable.models.Pet] - """ - - pets: Required[list["Pet"]] - """Required.""" - - -class RequestQueryNestedResponseBodyResponseNestedNext(TypedDict, total=False): # pylint: disable=name-too-long - """RequestQueryNestedResponseBodyResponseNestedNext. - - :ivar next_token: - :vartype next_token: str - """ - - nextToken: str diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/types.py deleted file mode 100644 index b01973310852..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/serverdrivenpagination/types.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 - -from typing import TYPE_CHECKING -from typing_extensions import Required, TypedDict - -if TYPE_CHECKING: - from ..types import Pet - - -class NestedLinkResponseNestedItems(TypedDict, total=False): - """NestedLinkResponseNestedItems. - - :ivar pets: Required. - :vartype pets: list[~payload.pageable.models.Pet] - """ - - pets: Required[list["Pet"]] - """Required.""" - - -class NestedLinkResponseNestedNext(TypedDict, total=False): - """NestedLinkResponseNestedNext. - - :ivar next: - :vartype next: str - """ - - next: str diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/types.py deleted file mode 100644 index 80f1fc4f61f2..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/types.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 - -from typing_extensions import Required, TypedDict - - -class Pet(TypedDict, total=False): - """Pet. - - :ivar id: Required. - :vartype id: str - :ivar name: Required. - :vartype name: str - """ - - id: Required[str] - """Required.""" - name: Required[str] - """Required.""" - - -class XmlPet(TypedDict, total=False): - """An XML pet item. - - :ivar id: Required. - :vartype id: str - :ivar name: Required. - :vartype name: str - """ - - id: Required[str] - """Required.""" - name: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/xmlpagination/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/xmlpagination/aio/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/xmlpagination/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/xmlpagination/aio/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/xmlpagination/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/xmlpagination/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/xmlpagination/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/payload/pageable/xmlpagination/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/pyproject.toml index a13b3e420fd8..fa935cab90c1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-pageable/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_utils/model_base.py index 6aefa8480069..bf13b102cf18 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/types.py deleted file mode 100644 index 08e0f39153be..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/payload/xml/types.py +++ /dev/null @@ -1,388 +0,0 @@ -# coding=utf-8 - -import datetime -from typing import TYPE_CHECKING, Union -from typing_extensions import Required, TypedDict - -if TYPE_CHECKING: - from .models import Status - - -class Author(TypedDict, total=False): - """Author model with a custom XML name. - - :ivar name: Required. - :vartype name: str - """ - - name: Required[str] - """Required.""" - - -class Book(TypedDict, total=False): - """Book model with a custom XML name. - - :ivar title: Required. - :vartype title: str - """ - - title: Required[str] - """Required.""" - - -class ModelWithArrayOfModel(TypedDict, total=False): - """§4.1 — Contains an array of models. - - :ivar items_property: Required. - :vartype items_property: ~payload.xml.models.SimpleModel - """ - - items: Required[list["SimpleModel"]] - """Required.""" - - -class ModelWithAttributes(TypedDict, total=False): - """§5.1 — Contains fields that are XML attributes. - - :ivar id1: Required. - :vartype id1: int - :ivar id2: Required. - :vartype id2: str - :ivar enabled: Required. - :vartype enabled: bool - """ - - id1: Required[int] - """Required.""" - id2: Required[str] - """Required.""" - enabled: Required[bool] - """Required.""" - - -class ModelWithDatetime(TypedDict, total=False): - """Contains datetime properties with different encodings. - - :ivar rfc3339: DateTime value with rfc3339 encoding. Required. - :vartype rfc3339: ~datetime.datetime - :ivar rfc7231: DateTime value with rfc7231 encoding. Required. - :vartype rfc7231: ~datetime.datetime - """ - - rfc3339: Required[datetime.datetime] - """DateTime value with rfc3339 encoding. Required.""" - rfc7231: Required[datetime.datetime] - """DateTime value with rfc7231 encoding. Required.""" - - -class ModelWithDictionary(TypedDict, total=False): - """Contains a dictionary of key value pairs. - - :ivar metadata: Required. - :vartype metadata: dict[str, str] - """ - - metadata: Required[dict[str, str]] - """Required.""" - - -class ModelWithEmptyArray(TypedDict, total=False): - """Contains an array of models that's supposed to be sent/received as an empty XML element. - - :ivar items_property: Required. - :vartype items_property: ~payload.xml.models.SimpleModel - """ - - items: Required[list["SimpleModel"]] - """Required.""" - - -class ModelWithEncodedNames(TypedDict, total=False): - """Uses encodedName instead of Xml.Name which is functionally equivalent. - - :ivar model_data: Required. - :vartype model_data: ~payload.xml.models.SimpleModel - :ivar colors: Required. - :vartype colors: list[str] - """ - - modelData: Required["SimpleModel"] - """Required.""" - colors: Required[list[str]] - """Required.""" - - -class ModelWithEnum(TypedDict, total=False): - """Contains a single property with an enum value. - - :ivar status: Required. Known values are: "pending", "success", and "error". - :vartype status: str or ~payload.xml.models.Status - """ - - status: Required[Union[str, "Status"]] - """Required. Known values are: \"pending\", \"success\", and \"error\".""" - - -class ModelWithNamespace(TypedDict, total=False): - """§6.1, §7.1 — Contains fields with XML namespace on the model. - - :ivar id: Required. - :vartype id: int - :ivar title: Required. - :vartype title: str - """ - - id: Required[int] - """Required.""" - title: Required[str] - """Required.""" - - -class ModelWithNamespaceOnProperties(TypedDict, total=False): - """§6.2, §7.2 — Contains fields with different XML namespaces on individual properties. - - :ivar id: Required. - :vartype id: int - :ivar title: Required. - :vartype title: str - :ivar author: Required. - :vartype author: str - """ - - id: Required[int] - """Required.""" - title: Required[str] - """Required.""" - author: Required[str] - """Required.""" - - -class ModelWithNestedModel(TypedDict, total=False): - """§2.1 — Contains a property that references another model. - - :ivar nested: Required. - :vartype nested: ~payload.xml.models.SimpleModel - """ - - nested: Required["SimpleModel"] - """Required.""" - - -class ModelWithOptionalField(TypedDict, total=False): - """Contains an optional field. - - :ivar item: Required. - :vartype item: str - :ivar value: - :vartype value: int - """ - - item: Required[str] - """Required.""" - value: int - - -class ModelWithRenamedArrays(TypedDict, total=False): - """§3.3, §3.4 — Contains fields of wrapped and unwrapped arrays of primitive types that have - different XML representations. - - :ivar colors: Required. - :vartype colors: list[str] - :ivar counts: Required. - :vartype counts: list[int] - """ - - colors: Required[list[str]] - """Required.""" - counts: Required[list[int]] - """Required.""" - - -class ModelWithRenamedAttribute(TypedDict, total=False): - """§5.2 — Contains a renamed XML attribute. - - :ivar id: Required. - :vartype id: int - :ivar title: Required. - :vartype title: str - :ivar author: Required. - :vartype author: str - """ - - id: Required[int] - """Required.""" - title: Required[str] - """Required.""" - author: Required[str] - """Required.""" - - -class ModelWithRenamedFields(TypedDict, total=False): - """§1.3, §2.3 — Contains fields of the same type that have different XML representation. - - :ivar input_data: Required. - :vartype input_data: ~payload.xml.models.SimpleModel - :ivar output_data: Required. - :vartype output_data: ~payload.xml.models.SimpleModel - """ - - inputData: Required["SimpleModel"] - """Required.""" - outputData: Required["SimpleModel"] - """Required.""" - - -class ModelWithRenamedNestedModel(TypedDict, total=False): - """§2.2 — Contains a property whose type has. - - :ivar author: Required. - :vartype author: ~payload.xml.models.Author - """ - - author: Required["Author"] - """Required.""" - - -class ModelWithRenamedProperty(TypedDict, total=False): - """§1.2 — Contains a scalar property with a custom XML name. - - :ivar title: Required. - :vartype title: str - :ivar author: Required. - :vartype author: str - """ - - title: Required[str] - """Required.""" - author: Required[str] - """Required.""" - - -class ModelWithRenamedUnwrappedModelArray(TypedDict, total=False): - """§4.4 — Contains an unwrapped array of models with a custom item name. - - :ivar items_property: Required. - :vartype items_property: ~payload.xml.models.SimpleModel - """ - - items: Required[list["SimpleModel"]] - """Required.""" - - -class ModelWithRenamedWrappedAndItemModelArray(TypedDict, total=False): - """§4.5 — Contains a wrapped array of models with custom wrapper and item names. - - :ivar books: Required. - :vartype books: ~payload.xml.models.Book - """ - - books: Required[list["Book"]] - """Required.""" - - -class ModelWithRenamedWrappedModelArray(TypedDict, total=False): - """§4.3 — Contains a wrapped array of models with a custom wrapper name. - - :ivar items_property: Required. - :vartype items_property: ~payload.xml.models.SimpleModel - """ - - items: Required[list["SimpleModel"]] - """Required.""" - - -class ModelWithSimpleArrays(TypedDict, total=False): - """§3.1 — Contains fields of arrays of primitive types. - - :ivar colors: Required. - :vartype colors: list[str] - :ivar counts: Required. - :vartype counts: list[int] - """ - - colors: Required[list[str]] - """Required.""" - counts: Required[list[int]] - """Required.""" - - -class ModelWithText(TypedDict, total=False): - """§8.1 — Contains an attribute and text. - - :ivar language: Required. - :vartype language: str - :ivar content: Required. - :vartype content: str - """ - - language: Required[str] - """Required.""" - content: Required[str] - """Required.""" - - -class ModelWithUnwrappedArray(TypedDict, total=False): - """§3.2 — Contains fields of wrapped and unwrapped arrays of primitive types. - - :ivar colors: Required. - :vartype colors: list[str] - :ivar counts: Required. - :vartype counts: list[int] - """ - - colors: Required[list[str]] - """Required.""" - counts: Required[list[int]] - """Required.""" - - -class ModelWithUnwrappedModelArray(TypedDict, total=False): - """§4.2 — Contains an unwrapped array of models. - - :ivar items_property: Required. - :vartype items_property: ~payload.xml.models.SimpleModel - """ - - items: Required[list["SimpleModel"]] - """Required.""" - - -class ModelWithWrappedPrimitiveCustomItemNames(TypedDict, total=False): - """§3.5 — Contains a wrapped primitive array with custom wrapper and item names. - - :ivar tags: Required. - :vartype tags: list[str] - """ - - tags: Required[list[str]] - """Required.""" - - -class SimpleModel(TypedDict, total=False): - """§1.1 — Contains fields of primitive types. - - :ivar name: Required. - :vartype name: str - :ivar age: Required. - :vartype age: int - """ - - name: Required[str] - """Required.""" - age: Required[int] - """Required.""" - - -class XmlErrorBody(TypedDict, total=False): - """The body of an XML error response. - - :ivar message: Required. - :vartype message: str - :ivar code: Required. - :vartype code: int - """ - - message: Required[str] - """Required.""" - code: Required[int] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/pyproject.toml index 7c8c79c9aa61..04cdb6f6f707 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/payload-xml/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/pyproject.toml index ef2a1de0e892..19ff5227bf8c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/types.py deleted file mode 100644 index 8a64fba89dad..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/response-status-code-range/response/statuscoderange/types.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 - -from typing_extensions import Required, TypedDict - - -class DefaultError(TypedDict, total=False): - """DefaultError. - - :ivar code: Required. - :vartype code: str - """ - - code: Required[str] - """Required.""" - - -class ErrorInRange(TypedDict, total=False): - """ErrorInRange. - - :ivar code: Required. - :vartype code: str - :ivar message: Required. - :vartype message: str - """ - - code: Required[str] - """Required.""" - message: Required[str] - """Required.""" - - -class NotFoundError(TypedDict, total=False): - """NotFoundError. - - :ivar code: Required. - :vartype code: str - :ivar resource_id: Required. - :vartype resource_id: str - """ - - code: Required[str] - """Required.""" - resourceId: Required[str] - """Required.""" - - -class Standard4XXError(TypedDict, total=False): - """Standard4XXError. - - :ivar code: Required. - :vartype code: str - """ - - code: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/pyproject.toml index 05b15249b90a..2878156e9d01 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/models/__init__.py new file mode 100644 index 000000000000..dfdc91967930 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/models/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + ExpandParameters, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ExpandParameters", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/models/_models.py new file mode 100644 index 000000000000..5603b1c6853d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/models/_models.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# pylint: disable=useless-super-delegation + +from typing import Any, Mapping, overload + +from .._utils.model_base import Model as _Model, rest_field + + +class ExpandParameters(_Model): + """A named model used to verify explode expansion of a model-valued query parameter. + + :ivar field: Required. + :vartype field: str + :ivar value: Required. + :vartype value: str + """ + + field: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + value: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + field: str, + value: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/models/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/models/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/explode/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/explode/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/explode/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/explode/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/standard/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/standard/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/standard/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/labelexpansion/standard/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/explode/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/explode/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/explode/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/explode/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/standard/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/standard/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/standard/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/matrixexpansion/standard/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/explode/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/explode/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/explode/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/explode/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/standard/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/standard/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/standard/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/pathexpansion/standard/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/reservedexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/reservedexpansion/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/reservedexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/reservedexpansion/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/reservedexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/reservedexpansion/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/reservedexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/reservedexpansion/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/explode/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/explode/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/explode/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/explode/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/standard/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/standard/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/standard/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/pathparameters/simpleexpansion/standard/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/explode/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/explode/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/explode/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/explode/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/standard/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/standard/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/standard/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/querycontinuation/standard/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_operations.py index e4f940f2f96d..4c7628c392eb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_operations.py @@ -14,10 +14,12 @@ from corehttp.runtime import AsyncPipelineClient from corehttp.runtime.pipeline import PipelineResponse +from ...... import models as _models5 from ......_utils.serialization import Deserializer, Serializer from ......aio._configuration import RoutesClientConfiguration from ...operations._operations import ( build_query_parameters_query_expansion_explode_array_request, + build_query_parameters_query_expansion_explode_model_request, build_query_parameters_query_expansion_explode_primitive_request, build_query_parameters_query_expansion_explode_record_request, ) @@ -174,3 +176,47 @@ async def record(self, *, param: dict[str, int], **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore + + async def model(self, *, param: _models5.ExpandParameters, **kwargs: Any) -> None: + """model. + + :keyword param: Required. + :paramtype param: ~routes.models.ExpandParameters + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_query_parameters_query_expansion_explode_model_request( + param=param, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/operations/_operations.py index f47781a5f090..5ac31ba15bab 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/operations/_operations.py @@ -15,6 +15,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict +from ..... import models as _models4 from ....._configuration import RoutesClientConfiguration from ....._utils.serialization import Deserializer, Serializer @@ -67,6 +68,20 @@ def build_query_parameters_query_expansion_explode_record_request( # pylint: di return HttpRequest(method="GET", url=_url, params=_params, **kwargs) +def build_query_parameters_query_expansion_explode_model_request( # pylint: disable=name-too-long + *, param: _models4.ExpandParameters, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/routes/query/query-expansion/explode/model" + + # Construct parameters + _params["param"] = _SERIALIZER.query("param", param, "ExpandParameters") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + class QueryParametersQueryExpansionExplodeOperations: # pylint: disable=name-too-long """ .. warning:: @@ -215,3 +230,49 @@ def record(self, *, param: dict[str, int], **kwargs: Any) -> None: # pylint: di if cls: return cls(pipeline_response, None, {}) # type: ignore + + def model( # pylint: disable=inconsistent-return-statements + self, *, param: _models4.ExpandParameters, **kwargs: Any + ) -> None: + """model. + + :keyword param: Required. + :paramtype param: ~routes.models.ExpandParameters + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_query_parameters_query_expansion_explode_model_request( + param=param, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/explode/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/standard/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/standard/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/standard/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/standard/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/standard/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/standard/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/standard/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/routes/routes/queryparameters/queryexpansion/standard/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/pyproject.toml index 800a3d970738..83022db677b8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/aio/operations/_operations.py index 975933c848d5..7c67cbc06186 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/aio/operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ...._utils.model_base import SdkJSONEncoder, _deserialize from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import JsonClientConfiguration from ...operations._operations import build_property_get_request, build_property_send_request -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -64,11 +63,13 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send( + self, body: _types_models2.JsonEncodedNameModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~serialization.encodedname.json.property.types.JsonEncodedNameModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -91,12 +92,14 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def send(self, body: Union[_models2.JsonEncodedNameModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def send( + self, body: Union[_models2.JsonEncodedNameModel, _types_models2.JsonEncodedNameModel, IO[bytes]], **kwargs: Any + ) -> None: """send. - :param body: Is one of the following types: JsonEncodedNameModel, JSON, IO[bytes] Required. - :type body: ~serialization.encodedname.json.property.models.JsonEncodedNameModel or JSON or - IO[bytes] + :param body: Is either a JsonEncodedNameModel type or a IO[bytes] type. Required. + :type body: ~serialization.encodedname.json.property.models.JsonEncodedNameModel or + ~serialization.encodedname.json.property.types.JsonEncodedNameModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/operations/_operations.py index 50b68f531f2e..b2fdcbaf72ae 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/operations/_operations.py @@ -19,12 +19,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from ..._configuration import JsonClientConfiguration from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -94,11 +93,13 @@ def send( """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send( + self, body: _types_models1.JsonEncodedNameModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~serialization.encodedname.json.property.types.JsonEncodedNameModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -122,13 +123,13 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ def send( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.JsonEncodedNameModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.JsonEncodedNameModel, _types_models1.JsonEncodedNameModel, IO[bytes]], **kwargs: Any ) -> None: """send. - :param body: Is one of the following types: JsonEncodedNameModel, JSON, IO[bytes] Required. - :type body: ~serialization.encodedname.json.property.models.JsonEncodedNameModel or JSON or - IO[bytes] + :param body: Is either a JsonEncodedNameModel type or a IO[bytes] type. Required. + :type body: ~serialization.encodedname.json.property.models.JsonEncodedNameModel or + ~serialization.encodedname.json.property.types.JsonEncodedNameModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/serialization-encoded-name-json/serialization/encodedname/json/property/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/pyproject.toml index 0893efe98f3e..c4afb84cf594 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-endpoint-not-defined/server/endpoint/notdefined/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/pyproject.toml index 0b2f49246225..b278ebbb9890 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-multiple/server/path/multiple/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/pyproject.toml index d1d04757d38d..7d23476ec2ec 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-path-single/server/path/single/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/pyproject.toml index 64ffd63928e8..e2944926a07c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-not-versioned/server/versions/notversioned/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/pyproject.toml index 6fcae26ae725..16eb6cf08b93 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/server-versions-versioned/server/versions/versioned/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setup.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setup.py index 2ab8095b48b4..5d71fd274461 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setup.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setup.py @@ -38,6 +38,7 @@ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "License :: OSI Approved :: MIT License", ], zip_safe=False, diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/setuppy-authentication-union/setuppy/authentication/union/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/pyproject.toml index 83ee64aeed35..67352b7b2d74 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-conditional-request/specialheaders/conditionalrequest/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/pyproject.toml index fa712cba243b..0a60de64eb01 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-headers-repeatability/specialheaders/repeatability/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/pyproject.toml index fa7b25b43491..dc2db8f452c5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_client.py index 082f811257dc..f62be8c77186 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_client.py @@ -62,7 +62,7 @@ class SpecialWordsClient: # pylint: disable=client-accepts-api-version-keyword try while with - yield. + yield :ivar models: ModelsOperations operations :vartype models: specialwords.operations.ModelsOperations diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_utils/model_base.py index 6aefa8480069..bf13b102cf18 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/_client.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/_client.py index 967c7d218adf..1593280e268c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/_client.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/_client.py @@ -62,7 +62,7 @@ class SpecialWordsClient: # pylint: disable=client-accepts-api-version-keyword try while with - yield. + yield :ivar models: ModelsOperations operations :vartype models: specialwords.aio.operations.ModelsOperations diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/aio/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/aio/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/models/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/models/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/extensiblestrings/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/aio/operations/_operations.py index 8c8730bfbf05..59f7f6df0d54 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/aio/operations/_operations.py @@ -17,7 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ...._utils.model_base import SdkJSONEncoder from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import SpecialWordsClientConfiguration @@ -27,7 +27,6 @@ build_model_properties_with_list_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -66,11 +65,13 @@ async def same_as_model( """ @overload - async def same_as_model(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def same_as_model( + self, body: _types_models2.SameAsModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """same_as_model. :param body: Required. - :type body: JSON + :type body: ~specialwords.modelproperties.types.SameAsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -93,11 +94,14 @@ async def same_as_model(self, body: IO[bytes], *, content_type: str = "applicati :raises ~corehttp.exceptions.HttpResponseError: """ - async def same_as_model(self, body: Union[_models2.SameAsModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def same_as_model( + self, body: Union[_models2.SameAsModel, _types_models2.SameAsModel, IO[bytes]], **kwargs: Any + ) -> None: """same_as_model. - :param body: Is one of the following types: SameAsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.modelproperties.models.SameAsModel or JSON or IO[bytes] + :param body: Is either a SameAsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.modelproperties.models.SameAsModel or + ~specialwords.modelproperties.types.SameAsModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -163,11 +167,13 @@ async def dict_methods( """ @overload - async def dict_methods(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def dict_methods( + self, body: _types_models2.DictMethods, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """dict_methods. :param body: Required. - :type body: JSON + :type body: ~specialwords.modelproperties.types.DictMethods :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -190,11 +196,14 @@ async def dict_methods(self, body: IO[bytes], *, content_type: str = "applicatio :raises ~corehttp.exceptions.HttpResponseError: """ - async def dict_methods(self, body: Union[_models2.DictMethods, JSON, IO[bytes]], **kwargs: Any) -> None: + async def dict_methods( + self, body: Union[_models2.DictMethods, _types_models2.DictMethods, IO[bytes]], **kwargs: Any + ) -> None: """dict_methods. - :param body: Is one of the following types: DictMethods, JSON, IO[bytes] Required. - :type body: ~specialwords.modelproperties.models.DictMethods or JSON or IO[bytes] + :param body: Is either a DictMethods type or a IO[bytes] type. Required. + :type body: ~specialwords.modelproperties.models.DictMethods or + ~specialwords.modelproperties.types.DictMethods or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -260,11 +269,13 @@ async def with_list( """ @overload - async def with_list(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_list( + self, body: _types_models2.ModelWithList, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_list. :param body: Required. - :type body: JSON + :type body: ~specialwords.modelproperties.types.ModelWithList :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -287,11 +298,14 @@ async def with_list(self, body: IO[bytes], *, content_type: str = "application/j :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_list(self, body: Union[_models2.ModelWithList, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_list( + self, body: Union[_models2.ModelWithList, _types_models2.ModelWithList, IO[bytes]], **kwargs: Any + ) -> None: """with_list. - :param body: Is one of the following types: ModelWithList, JSON, IO[bytes] Required. - :type body: ~specialwords.modelproperties.models.ModelWithList or JSON or IO[bytes] + :param body: Is either a ModelWithList type or a IO[bytes] type. Required. + :type body: ~specialwords.modelproperties.models.ModelWithList or + ~specialwords.modelproperties.types.ModelWithList or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/operations/_operations.py index d2e4fb6956e7..26afe4c42651 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/operations/_operations.py @@ -17,12 +17,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from ..._configuration import SpecialWordsClientConfiguration from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -106,11 +105,13 @@ def same_as_model( """ @overload - def same_as_model(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def same_as_model( + self, body: _types_models1.SameAsModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """same_as_model. :param body: Required. - :type body: JSON + :type body: ~specialwords.modelproperties.types.SameAsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -134,12 +135,13 @@ def same_as_model(self, body: IO[bytes], *, content_type: str = "application/jso """ def same_as_model( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.SameAsModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.SameAsModel, _types_models1.SameAsModel, IO[bytes]], **kwargs: Any ) -> None: """same_as_model. - :param body: Is one of the following types: SameAsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.modelproperties.models.SameAsModel or JSON or IO[bytes] + :param body: Is either a SameAsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.modelproperties.models.SameAsModel or + ~specialwords.modelproperties.types.SameAsModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -205,11 +207,13 @@ def dict_methods( """ @overload - def dict_methods(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def dict_methods( + self, body: _types_models1.DictMethods, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """dict_methods. :param body: Required. - :type body: JSON + :type body: ~specialwords.modelproperties.types.DictMethods :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -233,12 +237,13 @@ def dict_methods(self, body: IO[bytes], *, content_type: str = "application/json """ def dict_methods( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.DictMethods, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.DictMethods, _types_models1.DictMethods, IO[bytes]], **kwargs: Any ) -> None: """dict_methods. - :param body: Is one of the following types: DictMethods, JSON, IO[bytes] Required. - :type body: ~specialwords.modelproperties.models.DictMethods or JSON or IO[bytes] + :param body: Is either a DictMethods type or a IO[bytes] type. Required. + :type body: ~specialwords.modelproperties.models.DictMethods or + ~specialwords.modelproperties.types.DictMethods or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -302,11 +307,13 @@ def with_list(self, body: _models1.ModelWithList, *, content_type: str = "applic """ @overload - def with_list(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_list( + self, body: _types_models1.ModelWithList, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_list. :param body: Required. - :type body: JSON + :type body: ~specialwords.modelproperties.types.ModelWithList :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -330,12 +337,13 @@ def with_list(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_list( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.ModelWithList, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.ModelWithList, _types_models1.ModelWithList, IO[bytes]], **kwargs: Any ) -> None: """with_list. - :param body: Is one of the following types: ModelWithList, JSON, IO[bytes] Required. - :type body: ~specialwords.modelproperties.models.ModelWithList or JSON or IO[bytes] + :param body: Is either a ModelWithList type or a IO[bytes] type. Required. + :type body: ~specialwords.modelproperties.models.ModelWithList or + ~specialwords.modelproperties.types.ModelWithList or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/modelproperties/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/aio/operations/_operations.py index 8f46f72eabed..3efc18864c1c 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/aio/operations/_operations.py @@ -18,7 +18,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models2 +from ... import models as _models2, types as _types_models2 from ...._utils.model_base import SdkJSONEncoder from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import SpecialWordsClientConfiguration @@ -58,7 +58,6 @@ build_models_with_yield_request, ) -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -95,11 +94,13 @@ async def with_and(self, body: _models2.AndModel, *, content_type: str = "applic """ @overload - async def with_and(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_and( + self, body: _types_models2.AndModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_and. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.AndModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -122,11 +123,12 @@ async def with_and(self, body: IO[bytes], *, content_type: str = "application/js :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_and(self, body: Union[_models2.AndModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_and(self, body: Union[_models2.AndModel, _types_models2.AndModel, IO[bytes]], **kwargs: Any) -> None: """with_and. - :param body: Is one of the following types: AndModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.AndModel or JSON or IO[bytes] + :param body: Is either a AndModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.AndModel or ~specialwords.models.types.AndModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -190,11 +192,13 @@ async def with_as(self, body: _models2.AsModel, *, content_type: str = "applicat """ @overload - async def with_as(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_as( + self, body: _types_models2.AsModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_as. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.AsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -217,11 +221,12 @@ async def with_as(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_as(self, body: Union[_models2.AsModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_as(self, body: Union[_models2.AsModel, _types_models2.AsModel, IO[bytes]], **kwargs: Any) -> None: """with_as. - :param body: Is one of the following types: AsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.AsModel or JSON or IO[bytes] + :param body: Is either a AsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.AsModel or ~specialwords.models.types.AsModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -287,11 +292,13 @@ async def with_assert( """ @overload - async def with_assert(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_assert( + self, body: _types_models2.AssertModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_assert. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.AssertModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -314,11 +321,14 @@ async def with_assert(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_assert(self, body: Union[_models2.AssertModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_assert( + self, body: Union[_models2.AssertModel, _types_models2.AssertModel, IO[bytes]], **kwargs: Any + ) -> None: """with_assert. - :param body: Is one of the following types: AssertModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.AssertModel or JSON or IO[bytes] + :param body: Is either a AssertModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.AssertModel or ~specialwords.models.types.AssertModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -384,11 +394,13 @@ async def with_async( """ @overload - async def with_async(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_async( + self, body: _types_models2.AsyncModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_async. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.AsyncModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -411,11 +423,14 @@ async def with_async(self, body: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_async(self, body: Union[_models2.AsyncModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_async( + self, body: Union[_models2.AsyncModel, _types_models2.AsyncModel, IO[bytes]], **kwargs: Any + ) -> None: """with_async. - :param body: Is one of the following types: AsyncModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.AsyncModel or JSON or IO[bytes] + :param body: Is either a AsyncModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.AsyncModel or ~specialwords.models.types.AsyncModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -481,11 +496,13 @@ async def with_await( """ @overload - async def with_await(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_await( + self, body: _types_models2.AwaitModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_await. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.AwaitModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -508,11 +525,14 @@ async def with_await(self, body: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_await(self, body: Union[_models2.AwaitModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_await( + self, body: Union[_models2.AwaitModel, _types_models2.AwaitModel, IO[bytes]], **kwargs: Any + ) -> None: """with_await. - :param body: Is one of the following types: AwaitModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.AwaitModel or JSON or IO[bytes] + :param body: Is either a AwaitModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.AwaitModel or ~specialwords.models.types.AwaitModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -578,11 +598,13 @@ async def with_break( """ @overload - async def with_break(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_break( + self, body: _types_models2.BreakModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_break. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.BreakModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -605,11 +627,14 @@ async def with_break(self, body: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_break(self, body: Union[_models2.BreakModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_break( + self, body: Union[_models2.BreakModel, _types_models2.BreakModel, IO[bytes]], **kwargs: Any + ) -> None: """with_break. - :param body: Is one of the following types: BreakModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.BreakModel or JSON or IO[bytes] + :param body: Is either a BreakModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.BreakModel or ~specialwords.models.types.BreakModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -675,11 +700,13 @@ async def with_class( """ @overload - async def with_class(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_class( + self, body: _types_models2.ClassModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_class. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ClassModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -702,11 +729,14 @@ async def with_class(self, body: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_class(self, body: Union[_models2.ClassModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_class( + self, body: Union[_models2.ClassModel, _types_models2.ClassModel, IO[bytes]], **kwargs: Any + ) -> None: """with_class. - :param body: Is one of the following types: ClassModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ClassModel or JSON or IO[bytes] + :param body: Is either a ClassModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ClassModel or ~specialwords.models.types.ClassModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -772,11 +802,13 @@ async def with_constructor( """ @overload - async def with_constructor(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_constructor( + self, body: _types_models2.Constructor, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_constructor. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.Constructor :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -799,11 +831,14 @@ async def with_constructor(self, body: IO[bytes], *, content_type: str = "applic :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_constructor(self, body: Union[_models2.Constructor, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_constructor( + self, body: Union[_models2.Constructor, _types_models2.Constructor, IO[bytes]], **kwargs: Any + ) -> None: """with_constructor. - :param body: Is one of the following types: Constructor, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.Constructor or JSON or IO[bytes] + :param body: Is either a Constructor type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.Constructor or ~specialwords.models.types.Constructor + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -869,11 +904,13 @@ async def with_continue( """ @overload - async def with_continue(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_continue( + self, body: _types_models2.ContinueModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_continue. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ContinueModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -896,11 +933,14 @@ async def with_continue(self, body: IO[bytes], *, content_type: str = "applicati :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_continue(self, body: Union[_models2.ContinueModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_continue( + self, body: Union[_models2.ContinueModel, _types_models2.ContinueModel, IO[bytes]], **kwargs: Any + ) -> None: """with_continue. - :param body: Is one of the following types: ContinueModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ContinueModel or JSON or IO[bytes] + :param body: Is either a ContinueModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ContinueModel or + ~specialwords.models.types.ContinueModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -964,11 +1004,13 @@ async def with_def(self, body: _models2.DefModel, *, content_type: str = "applic """ @overload - async def with_def(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_def( + self, body: _types_models2.DefModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_def. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.DefModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -991,11 +1033,12 @@ async def with_def(self, body: IO[bytes], *, content_type: str = "application/js :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_def(self, body: Union[_models2.DefModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_def(self, body: Union[_models2.DefModel, _types_models2.DefModel, IO[bytes]], **kwargs: Any) -> None: """with_def. - :param body: Is one of the following types: DefModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.DefModel or JSON or IO[bytes] + :param body: Is either a DefModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.DefModel or ~specialwords.models.types.DefModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1059,11 +1102,13 @@ async def with_del(self, body: _models2.DelModel, *, content_type: str = "applic """ @overload - async def with_del(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_del( + self, body: _types_models2.DelModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_del. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.DelModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1086,11 +1131,12 @@ async def with_del(self, body: IO[bytes], *, content_type: str = "application/js :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_del(self, body: Union[_models2.DelModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_del(self, body: Union[_models2.DelModel, _types_models2.DelModel, IO[bytes]], **kwargs: Any) -> None: """with_del. - :param body: Is one of the following types: DelModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.DelModel or JSON or IO[bytes] + :param body: Is either a DelModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.DelModel or ~specialwords.models.types.DelModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1156,11 +1202,13 @@ async def with_elif( """ @overload - async def with_elif(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_elif( + self, body: _types_models2.ElifModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_elif. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ElifModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1183,11 +1231,14 @@ async def with_elif(self, body: IO[bytes], *, content_type: str = "application/j :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_elif(self, body: Union[_models2.ElifModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_elif( + self, body: Union[_models2.ElifModel, _types_models2.ElifModel, IO[bytes]], **kwargs: Any + ) -> None: """with_elif. - :param body: Is one of the following types: ElifModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ElifModel or JSON or IO[bytes] + :param body: Is either a ElifModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ElifModel or ~specialwords.models.types.ElifModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1253,11 +1304,13 @@ async def with_else( """ @overload - async def with_else(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_else( + self, body: _types_models2.ElseModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_else. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ElseModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1280,11 +1333,14 @@ async def with_else(self, body: IO[bytes], *, content_type: str = "application/j :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_else(self, body: Union[_models2.ElseModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_else( + self, body: Union[_models2.ElseModel, _types_models2.ElseModel, IO[bytes]], **kwargs: Any + ) -> None: """with_else. - :param body: Is one of the following types: ElseModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ElseModel or JSON or IO[bytes] + :param body: Is either a ElseModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ElseModel or ~specialwords.models.types.ElseModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1350,11 +1406,13 @@ async def with_except( """ @overload - async def with_except(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_except( + self, body: _types_models2.ExceptModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_except. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ExceptModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1377,11 +1435,14 @@ async def with_except(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_except(self, body: Union[_models2.ExceptModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_except( + self, body: Union[_models2.ExceptModel, _types_models2.ExceptModel, IO[bytes]], **kwargs: Any + ) -> None: """with_except. - :param body: Is one of the following types: ExceptModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ExceptModel or JSON or IO[bytes] + :param body: Is either a ExceptModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ExceptModel or ~specialwords.models.types.ExceptModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1447,11 +1508,13 @@ async def with_exec( """ @overload - async def with_exec(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_exec( + self, body: _types_models2.ExecModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_exec. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ExecModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1474,11 +1537,14 @@ async def with_exec(self, body: IO[bytes], *, content_type: str = "application/j :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_exec(self, body: Union[_models2.ExecModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_exec( + self, body: Union[_models2.ExecModel, _types_models2.ExecModel, IO[bytes]], **kwargs: Any + ) -> None: """with_exec. - :param body: Is one of the following types: ExecModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ExecModel or JSON or IO[bytes] + :param body: Is either a ExecModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ExecModel or ~specialwords.models.types.ExecModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1544,11 +1610,13 @@ async def with_finally( """ @overload - async def with_finally(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_finally( + self, body: _types_models2.FinallyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_finally. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.FinallyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1571,11 +1639,14 @@ async def with_finally(self, body: IO[bytes], *, content_type: str = "applicatio :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_finally(self, body: Union[_models2.FinallyModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_finally( + self, body: Union[_models2.FinallyModel, _types_models2.FinallyModel, IO[bytes]], **kwargs: Any + ) -> None: """with_finally. - :param body: Is one of the following types: FinallyModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.FinallyModel or JSON or IO[bytes] + :param body: Is either a FinallyModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.FinallyModel or ~specialwords.models.types.FinallyModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1639,11 +1710,13 @@ async def with_for(self, body: _models2.ForModel, *, content_type: str = "applic """ @overload - async def with_for(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_for( + self, body: _types_models2.ForModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_for. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ForModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1666,11 +1739,12 @@ async def with_for(self, body: IO[bytes], *, content_type: str = "application/js :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_for(self, body: Union[_models2.ForModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_for(self, body: Union[_models2.ForModel, _types_models2.ForModel, IO[bytes]], **kwargs: Any) -> None: """with_for. - :param body: Is one of the following types: ForModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ForModel or JSON or IO[bytes] + :param body: Is either a ForModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ForModel or ~specialwords.models.types.ForModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1736,11 +1810,13 @@ async def with_from( """ @overload - async def with_from(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_from( + self, body: _types_models2.FromModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_from. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.FromModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1763,11 +1839,14 @@ async def with_from(self, body: IO[bytes], *, content_type: str = "application/j :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_from(self, body: Union[_models2.FromModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_from( + self, body: Union[_models2.FromModel, _types_models2.FromModel, IO[bytes]], **kwargs: Any + ) -> None: """with_from. - :param body: Is one of the following types: FromModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.FromModel or JSON or IO[bytes] + :param body: Is either a FromModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.FromModel or ~specialwords.models.types.FromModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1833,11 +1912,13 @@ async def with_global( """ @overload - async def with_global(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_global( + self, body: _types_models2.GlobalModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_global. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.GlobalModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1860,11 +1941,14 @@ async def with_global(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_global(self, body: Union[_models2.GlobalModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_global( + self, body: Union[_models2.GlobalModel, _types_models2.GlobalModel, IO[bytes]], **kwargs: Any + ) -> None: """with_global. - :param body: Is one of the following types: GlobalModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.GlobalModel or JSON or IO[bytes] + :param body: Is either a GlobalModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.GlobalModel or ~specialwords.models.types.GlobalModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1928,11 +2012,13 @@ async def with_if(self, body: _models2.IfModel, *, content_type: str = "applicat """ @overload - async def with_if(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_if( + self, body: _types_models2.IfModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_if. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.IfModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1955,11 +2041,12 @@ async def with_if(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_if(self, body: Union[_models2.IfModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_if(self, body: Union[_models2.IfModel, _types_models2.IfModel, IO[bytes]], **kwargs: Any) -> None: """with_if. - :param body: Is one of the following types: IfModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.IfModel or JSON or IO[bytes] + :param body: Is either a IfModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.IfModel or ~specialwords.models.types.IfModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2025,11 +2112,13 @@ async def with_import( """ @overload - async def with_import(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_import( + self, body: _types_models2.ImportModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_import. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ImportModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2052,11 +2141,14 @@ async def with_import(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_import(self, body: Union[_models2.ImportModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_import( + self, body: Union[_models2.ImportModel, _types_models2.ImportModel, IO[bytes]], **kwargs: Any + ) -> None: """with_import. - :param body: Is one of the following types: ImportModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ImportModel or JSON or IO[bytes] + :param body: Is either a ImportModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ImportModel or ~specialwords.models.types.ImportModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2120,11 +2212,13 @@ async def with_in(self, body: _models2.InModel, *, content_type: str = "applicat """ @overload - async def with_in(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_in( + self, body: _types_models2.InModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_in. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.InModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2147,11 +2241,12 @@ async def with_in(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_in(self, body: Union[_models2.InModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_in(self, body: Union[_models2.InModel, _types_models2.InModel, IO[bytes]], **kwargs: Any) -> None: """with_in. - :param body: Is one of the following types: InModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.InModel or JSON or IO[bytes] + :param body: Is either a InModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.InModel or ~specialwords.models.types.InModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2215,11 +2310,13 @@ async def with_is(self, body: _models2.IsModel, *, content_type: str = "applicat """ @overload - async def with_is(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_is( + self, body: _types_models2.IsModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_is. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.IsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2242,11 +2339,12 @@ async def with_is(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_is(self, body: Union[_models2.IsModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_is(self, body: Union[_models2.IsModel, _types_models2.IsModel, IO[bytes]], **kwargs: Any) -> None: """with_is. - :param body: Is one of the following types: IsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.IsModel or JSON or IO[bytes] + :param body: Is either a IsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.IsModel or ~specialwords.models.types.IsModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2312,11 +2410,13 @@ async def with_lambda( """ @overload - async def with_lambda(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_lambda( + self, body: _types_models2.LambdaModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_lambda. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.LambdaModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2339,11 +2439,14 @@ async def with_lambda(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_lambda(self, body: Union[_models2.LambdaModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_lambda( + self, body: Union[_models2.LambdaModel, _types_models2.LambdaModel, IO[bytes]], **kwargs: Any + ) -> None: """with_lambda. - :param body: Is one of the following types: LambdaModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.LambdaModel or JSON or IO[bytes] + :param body: Is either a LambdaModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.LambdaModel or ~specialwords.models.types.LambdaModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2407,11 +2510,13 @@ async def with_not(self, body: _models2.NotModel, *, content_type: str = "applic """ @overload - async def with_not(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_not( + self, body: _types_models2.NotModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_not. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.NotModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2434,11 +2539,12 @@ async def with_not(self, body: IO[bytes], *, content_type: str = "application/js :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_not(self, body: Union[_models2.NotModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_not(self, body: Union[_models2.NotModel, _types_models2.NotModel, IO[bytes]], **kwargs: Any) -> None: """with_not. - :param body: Is one of the following types: NotModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.NotModel or JSON or IO[bytes] + :param body: Is either a NotModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.NotModel or ~specialwords.models.types.NotModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2502,11 +2608,13 @@ async def with_or(self, body: _models2.OrModel, *, content_type: str = "applicat """ @overload - async def with_or(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_or( + self, body: _types_models2.OrModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_or. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.OrModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2529,11 +2637,12 @@ async def with_or(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_or(self, body: Union[_models2.OrModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_or(self, body: Union[_models2.OrModel, _types_models2.OrModel, IO[bytes]], **kwargs: Any) -> None: """with_or. - :param body: Is one of the following types: OrModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.OrModel or JSON or IO[bytes] + :param body: Is either a OrModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.OrModel or ~specialwords.models.types.OrModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2599,11 +2708,13 @@ async def with_pass( """ @overload - async def with_pass(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_pass( + self, body: _types_models2.PassModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_pass. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.PassModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2626,11 +2737,14 @@ async def with_pass(self, body: IO[bytes], *, content_type: str = "application/j :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_pass(self, body: Union[_models2.PassModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_pass( + self, body: Union[_models2.PassModel, _types_models2.PassModel, IO[bytes]], **kwargs: Any + ) -> None: """with_pass. - :param body: Is one of the following types: PassModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.PassModel or JSON or IO[bytes] + :param body: Is either a PassModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.PassModel or ~specialwords.models.types.PassModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2696,11 +2810,13 @@ async def with_raise( """ @overload - async def with_raise(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_raise( + self, body: _types_models2.RaiseModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_raise. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.RaiseModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2723,11 +2839,14 @@ async def with_raise(self, body: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_raise(self, body: Union[_models2.RaiseModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_raise( + self, body: Union[_models2.RaiseModel, _types_models2.RaiseModel, IO[bytes]], **kwargs: Any + ) -> None: """with_raise. - :param body: Is one of the following types: RaiseModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.RaiseModel or JSON or IO[bytes] + :param body: Is either a RaiseModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.RaiseModel or ~specialwords.models.types.RaiseModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2793,11 +2912,13 @@ async def with_return( """ @overload - async def with_return(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_return( + self, body: _types_models2.ReturnModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_return. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ReturnModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2820,11 +2941,14 @@ async def with_return(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_return(self, body: Union[_models2.ReturnModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_return( + self, body: Union[_models2.ReturnModel, _types_models2.ReturnModel, IO[bytes]], **kwargs: Any + ) -> None: """with_return. - :param body: Is one of the following types: ReturnModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ReturnModel or JSON or IO[bytes] + :param body: Is either a ReturnModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ReturnModel or ~specialwords.models.types.ReturnModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2888,11 +3012,13 @@ async def with_try(self, body: _models2.TryModel, *, content_type: str = "applic """ @overload - async def with_try(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_try( + self, body: _types_models2.TryModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_try. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.TryModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2915,11 +3041,12 @@ async def with_try(self, body: IO[bytes], *, content_type: str = "application/js :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_try(self, body: Union[_models2.TryModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_try(self, body: Union[_models2.TryModel, _types_models2.TryModel, IO[bytes]], **kwargs: Any) -> None: """with_try. - :param body: Is one of the following types: TryModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.TryModel or JSON or IO[bytes] + :param body: Is either a TryModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.TryModel or ~specialwords.models.types.TryModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2985,11 +3112,13 @@ async def with_while( """ @overload - async def with_while(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_while( + self, body: _types_models2.WhileModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_while. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.WhileModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3012,11 +3141,14 @@ async def with_while(self, body: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_while(self, body: Union[_models2.WhileModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_while( + self, body: Union[_models2.WhileModel, _types_models2.WhileModel, IO[bytes]], **kwargs: Any + ) -> None: """with_while. - :param body: Is one of the following types: WhileModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.WhileModel or JSON or IO[bytes] + :param body: Is either a WhileModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.WhileModel or ~specialwords.models.types.WhileModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3082,11 +3214,13 @@ async def with_with( """ @overload - async def with_with(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_with( + self, body: _types_models2.WithModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_with. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.WithModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3109,11 +3243,14 @@ async def with_with(self, body: IO[bytes], *, content_type: str = "application/j :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_with(self, body: Union[_models2.WithModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_with( + self, body: Union[_models2.WithModel, _types_models2.WithModel, IO[bytes]], **kwargs: Any + ) -> None: """with_with. - :param body: Is one of the following types: WithModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.WithModel or JSON or IO[bytes] + :param body: Is either a WithModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.WithModel or ~specialwords.models.types.WithModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3179,11 +3316,13 @@ async def with_yield( """ @overload - async def with_yield(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_yield( + self, body: _types_models2.YieldModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_yield. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.YieldModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3206,11 +3345,14 @@ async def with_yield(self, body: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def with_yield(self, body: Union[_models2.YieldModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def with_yield( + self, body: Union[_models2.YieldModel, _types_models2.YieldModel, IO[bytes]], **kwargs: Any + ) -> None: """with_yield. - :param body: Is one of the following types: YieldModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.YieldModel or JSON or IO[bytes] + :param body: Is either a YieldModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.YieldModel or ~specialwords.models.types.YieldModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/operations/_operations.py index 76c90b503817..811c7d424599 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/operations/_operations.py @@ -18,12 +18,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models1 +from .. import models as _models1, types as _types_models1 from ..._configuration import SpecialWordsClientConfiguration from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -525,11 +524,11 @@ def with_and(self, body: _models1.AndModel, *, content_type: str = "application/ """ @overload - def with_and(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_and(self, body: _types_models1.AndModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_and. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.AndModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -553,12 +552,13 @@ def with_and(self, body: IO[bytes], *, content_type: str = "application/json", * """ def with_and( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.AndModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.AndModel, _types_models1.AndModel, IO[bytes]], **kwargs: Any ) -> None: """with_and. - :param body: Is one of the following types: AndModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.AndModel or JSON or IO[bytes] + :param body: Is either a AndModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.AndModel or ~specialwords.models.types.AndModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -622,11 +622,11 @@ def with_as(self, body: _models1.AsModel, *, content_type: str = "application/js """ @overload - def with_as(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_as(self, body: _types_models1.AsModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_as. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.AsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -650,12 +650,13 @@ def with_as(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def with_as( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.AsModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.AsModel, _types_models1.AsModel, IO[bytes]], **kwargs: Any ) -> None: """with_as. - :param body: Is one of the following types: AsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.AsModel or JSON or IO[bytes] + :param body: Is either a AsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.AsModel or ~specialwords.models.types.AsModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -719,11 +720,13 @@ def with_assert(self, body: _models1.AssertModel, *, content_type: str = "applic """ @overload - def with_assert(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_assert( + self, body: _types_models1.AssertModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_assert. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.AssertModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -747,12 +750,13 @@ def with_assert(self, body: IO[bytes], *, content_type: str = "application/json" """ def with_assert( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.AssertModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.AssertModel, _types_models1.AssertModel, IO[bytes]], **kwargs: Any ) -> None: """with_assert. - :param body: Is one of the following types: AssertModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.AssertModel or JSON or IO[bytes] + :param body: Is either a AssertModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.AssertModel or ~specialwords.models.types.AssertModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -816,11 +820,13 @@ def with_async(self, body: _models1.AsyncModel, *, content_type: str = "applicat """ @overload - def with_async(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_async( + self, body: _types_models1.AsyncModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_async. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.AsyncModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -844,12 +850,13 @@ def with_async(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_async( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.AsyncModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.AsyncModel, _types_models1.AsyncModel, IO[bytes]], **kwargs: Any ) -> None: """with_async. - :param body: Is one of the following types: AsyncModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.AsyncModel or JSON or IO[bytes] + :param body: Is either a AsyncModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.AsyncModel or ~specialwords.models.types.AsyncModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -913,11 +920,13 @@ def with_await(self, body: _models1.AwaitModel, *, content_type: str = "applicat """ @overload - def with_await(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_await( + self, body: _types_models1.AwaitModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_await. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.AwaitModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -941,12 +950,13 @@ def with_await(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_await( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.AwaitModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.AwaitModel, _types_models1.AwaitModel, IO[bytes]], **kwargs: Any ) -> None: """with_await. - :param body: Is one of the following types: AwaitModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.AwaitModel or JSON or IO[bytes] + :param body: Is either a AwaitModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.AwaitModel or ~specialwords.models.types.AwaitModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1010,11 +1020,13 @@ def with_break(self, body: _models1.BreakModel, *, content_type: str = "applicat """ @overload - def with_break(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_break( + self, body: _types_models1.BreakModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_break. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.BreakModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1038,12 +1050,13 @@ def with_break(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_break( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.BreakModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.BreakModel, _types_models1.BreakModel, IO[bytes]], **kwargs: Any ) -> None: """with_break. - :param body: Is one of the following types: BreakModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.BreakModel or JSON or IO[bytes] + :param body: Is either a BreakModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.BreakModel or ~specialwords.models.types.BreakModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1107,11 +1120,13 @@ def with_class(self, body: _models1.ClassModel, *, content_type: str = "applicat """ @overload - def with_class(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_class( + self, body: _types_models1.ClassModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_class. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ClassModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1135,12 +1150,13 @@ def with_class(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_class( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.ClassModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.ClassModel, _types_models1.ClassModel, IO[bytes]], **kwargs: Any ) -> None: """with_class. - :param body: Is one of the following types: ClassModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ClassModel or JSON or IO[bytes] + :param body: Is either a ClassModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ClassModel or ~specialwords.models.types.ClassModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1206,11 +1222,13 @@ def with_constructor( """ @overload - def with_constructor(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_constructor( + self, body: _types_models1.Constructor, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_constructor. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.Constructor :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1234,12 +1252,13 @@ def with_constructor(self, body: IO[bytes], *, content_type: str = "application/ """ def with_constructor( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.Constructor, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.Constructor, _types_models1.Constructor, IO[bytes]], **kwargs: Any ) -> None: """with_constructor. - :param body: Is one of the following types: Constructor, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.Constructor or JSON or IO[bytes] + :param body: Is either a Constructor type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.Constructor or ~specialwords.models.types.Constructor + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1305,11 +1324,13 @@ def with_continue( """ @overload - def with_continue(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_continue( + self, body: _types_models1.ContinueModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_continue. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ContinueModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1333,12 +1354,13 @@ def with_continue(self, body: IO[bytes], *, content_type: str = "application/jso """ def with_continue( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.ContinueModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.ContinueModel, _types_models1.ContinueModel, IO[bytes]], **kwargs: Any ) -> None: """with_continue. - :param body: Is one of the following types: ContinueModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ContinueModel or JSON or IO[bytes] + :param body: Is either a ContinueModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ContinueModel or + ~specialwords.models.types.ContinueModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1402,11 +1424,11 @@ def with_def(self, body: _models1.DefModel, *, content_type: str = "application/ """ @overload - def with_def(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_def(self, body: _types_models1.DefModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_def. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.DefModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1430,12 +1452,13 @@ def with_def(self, body: IO[bytes], *, content_type: str = "application/json", * """ def with_def( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.DefModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.DefModel, _types_models1.DefModel, IO[bytes]], **kwargs: Any ) -> None: """with_def. - :param body: Is one of the following types: DefModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.DefModel or JSON or IO[bytes] + :param body: Is either a DefModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.DefModel or ~specialwords.models.types.DefModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1499,11 +1522,11 @@ def with_del(self, body: _models1.DelModel, *, content_type: str = "application/ """ @overload - def with_del(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_del(self, body: _types_models1.DelModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_del. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.DelModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1527,12 +1550,13 @@ def with_del(self, body: IO[bytes], *, content_type: str = "application/json", * """ def with_del( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.DelModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.DelModel, _types_models1.DelModel, IO[bytes]], **kwargs: Any ) -> None: """with_del. - :param body: Is one of the following types: DelModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.DelModel or JSON or IO[bytes] + :param body: Is either a DelModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.DelModel or ~specialwords.models.types.DelModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1596,11 +1620,13 @@ def with_elif(self, body: _models1.ElifModel, *, content_type: str = "applicatio """ @overload - def with_elif(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_elif( + self, body: _types_models1.ElifModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_elif. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ElifModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1624,12 +1650,13 @@ def with_elif(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_elif( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.ElifModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.ElifModel, _types_models1.ElifModel, IO[bytes]], **kwargs: Any ) -> None: """with_elif. - :param body: Is one of the following types: ElifModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ElifModel or JSON or IO[bytes] + :param body: Is either a ElifModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ElifModel or ~specialwords.models.types.ElifModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1693,11 +1720,13 @@ def with_else(self, body: _models1.ElseModel, *, content_type: str = "applicatio """ @overload - def with_else(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_else( + self, body: _types_models1.ElseModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_else. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ElseModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1721,12 +1750,13 @@ def with_else(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_else( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.ElseModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.ElseModel, _types_models1.ElseModel, IO[bytes]], **kwargs: Any ) -> None: """with_else. - :param body: Is one of the following types: ElseModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ElseModel or JSON or IO[bytes] + :param body: Is either a ElseModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ElseModel or ~specialwords.models.types.ElseModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1790,11 +1820,13 @@ def with_except(self, body: _models1.ExceptModel, *, content_type: str = "applic """ @overload - def with_except(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_except( + self, body: _types_models1.ExceptModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_except. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ExceptModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1818,12 +1850,13 @@ def with_except(self, body: IO[bytes], *, content_type: str = "application/json" """ def with_except( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.ExceptModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.ExceptModel, _types_models1.ExceptModel, IO[bytes]], **kwargs: Any ) -> None: """with_except. - :param body: Is one of the following types: ExceptModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ExceptModel or JSON or IO[bytes] + :param body: Is either a ExceptModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ExceptModel or ~specialwords.models.types.ExceptModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1887,11 +1920,13 @@ def with_exec(self, body: _models1.ExecModel, *, content_type: str = "applicatio """ @overload - def with_exec(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_exec( + self, body: _types_models1.ExecModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_exec. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ExecModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1915,12 +1950,13 @@ def with_exec(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_exec( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.ExecModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.ExecModel, _types_models1.ExecModel, IO[bytes]], **kwargs: Any ) -> None: """with_exec. - :param body: Is one of the following types: ExecModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ExecModel or JSON or IO[bytes] + :param body: Is either a ExecModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ExecModel or ~specialwords.models.types.ExecModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1986,11 +2022,13 @@ def with_finally( """ @overload - def with_finally(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_finally( + self, body: _types_models1.FinallyModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_finally. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.FinallyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2014,12 +2052,13 @@ def with_finally(self, body: IO[bytes], *, content_type: str = "application/json """ def with_finally( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.FinallyModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.FinallyModel, _types_models1.FinallyModel, IO[bytes]], **kwargs: Any ) -> None: """with_finally. - :param body: Is one of the following types: FinallyModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.FinallyModel or JSON or IO[bytes] + :param body: Is either a FinallyModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.FinallyModel or ~specialwords.models.types.FinallyModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2083,11 +2122,11 @@ def with_for(self, body: _models1.ForModel, *, content_type: str = "application/ """ @overload - def with_for(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_for(self, body: _types_models1.ForModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_for. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ForModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2111,12 +2150,13 @@ def with_for(self, body: IO[bytes], *, content_type: str = "application/json", * """ def with_for( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.ForModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.ForModel, _types_models1.ForModel, IO[bytes]], **kwargs: Any ) -> None: """with_for. - :param body: Is one of the following types: ForModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ForModel or JSON or IO[bytes] + :param body: Is either a ForModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ForModel or ~specialwords.models.types.ForModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2180,11 +2220,13 @@ def with_from(self, body: _models1.FromModel, *, content_type: str = "applicatio """ @overload - def with_from(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_from( + self, body: _types_models1.FromModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_from. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.FromModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2208,12 +2250,13 @@ def with_from(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_from( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.FromModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.FromModel, _types_models1.FromModel, IO[bytes]], **kwargs: Any ) -> None: """with_from. - :param body: Is one of the following types: FromModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.FromModel or JSON or IO[bytes] + :param body: Is either a FromModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.FromModel or ~specialwords.models.types.FromModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2277,11 +2320,13 @@ def with_global(self, body: _models1.GlobalModel, *, content_type: str = "applic """ @overload - def with_global(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_global( + self, body: _types_models1.GlobalModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_global. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.GlobalModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2305,12 +2350,13 @@ def with_global(self, body: IO[bytes], *, content_type: str = "application/json" """ def with_global( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.GlobalModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.GlobalModel, _types_models1.GlobalModel, IO[bytes]], **kwargs: Any ) -> None: """with_global. - :param body: Is one of the following types: GlobalModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.GlobalModel or JSON or IO[bytes] + :param body: Is either a GlobalModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.GlobalModel or ~specialwords.models.types.GlobalModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2374,11 +2420,11 @@ def with_if(self, body: _models1.IfModel, *, content_type: str = "application/js """ @overload - def with_if(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_if(self, body: _types_models1.IfModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_if. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.IfModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2402,12 +2448,13 @@ def with_if(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def with_if( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.IfModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.IfModel, _types_models1.IfModel, IO[bytes]], **kwargs: Any ) -> None: """with_if. - :param body: Is one of the following types: IfModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.IfModel or JSON or IO[bytes] + :param body: Is either a IfModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.IfModel or ~specialwords.models.types.IfModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2471,11 +2518,13 @@ def with_import(self, body: _models1.ImportModel, *, content_type: str = "applic """ @overload - def with_import(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_import( + self, body: _types_models1.ImportModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_import. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ImportModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2499,12 +2548,13 @@ def with_import(self, body: IO[bytes], *, content_type: str = "application/json" """ def with_import( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.ImportModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.ImportModel, _types_models1.ImportModel, IO[bytes]], **kwargs: Any ) -> None: """with_import. - :param body: Is one of the following types: ImportModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ImportModel or JSON or IO[bytes] + :param body: Is either a ImportModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ImportModel or ~specialwords.models.types.ImportModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2568,11 +2618,11 @@ def with_in(self, body: _models1.InModel, *, content_type: str = "application/js """ @overload - def with_in(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_in(self, body: _types_models1.InModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_in. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.InModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2596,12 +2646,13 @@ def with_in(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def with_in( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.InModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.InModel, _types_models1.InModel, IO[bytes]], **kwargs: Any ) -> None: """with_in. - :param body: Is one of the following types: InModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.InModel or JSON or IO[bytes] + :param body: Is either a InModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.InModel or ~specialwords.models.types.InModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2665,11 +2716,11 @@ def with_is(self, body: _models1.IsModel, *, content_type: str = "application/js """ @overload - def with_is(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_is(self, body: _types_models1.IsModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_is. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.IsModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2693,12 +2744,13 @@ def with_is(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def with_is( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.IsModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.IsModel, _types_models1.IsModel, IO[bytes]], **kwargs: Any ) -> None: """with_is. - :param body: Is one of the following types: IsModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.IsModel or JSON or IO[bytes] + :param body: Is either a IsModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.IsModel or ~specialwords.models.types.IsModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2762,11 +2814,13 @@ def with_lambda(self, body: _models1.LambdaModel, *, content_type: str = "applic """ @overload - def with_lambda(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_lambda( + self, body: _types_models1.LambdaModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_lambda. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.LambdaModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2790,12 +2844,13 @@ def with_lambda(self, body: IO[bytes], *, content_type: str = "application/json" """ def with_lambda( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.LambdaModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.LambdaModel, _types_models1.LambdaModel, IO[bytes]], **kwargs: Any ) -> None: """with_lambda. - :param body: Is one of the following types: LambdaModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.LambdaModel or JSON or IO[bytes] + :param body: Is either a LambdaModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.LambdaModel or ~specialwords.models.types.LambdaModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2859,11 +2914,11 @@ def with_not(self, body: _models1.NotModel, *, content_type: str = "application/ """ @overload - def with_not(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_not(self, body: _types_models1.NotModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_not. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.NotModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2887,12 +2942,13 @@ def with_not(self, body: IO[bytes], *, content_type: str = "application/json", * """ def with_not( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.NotModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.NotModel, _types_models1.NotModel, IO[bytes]], **kwargs: Any ) -> None: """with_not. - :param body: Is one of the following types: NotModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.NotModel or JSON or IO[bytes] + :param body: Is either a NotModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.NotModel or ~specialwords.models.types.NotModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2956,11 +3012,11 @@ def with_or(self, body: _models1.OrModel, *, content_type: str = "application/js """ @overload - def with_or(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_or(self, body: _types_models1.OrModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_or. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.OrModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2984,12 +3040,13 @@ def with_or(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def with_or( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.OrModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.OrModel, _types_models1.OrModel, IO[bytes]], **kwargs: Any ) -> None: """with_or. - :param body: Is one of the following types: OrModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.OrModel or JSON or IO[bytes] + :param body: Is either a OrModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.OrModel or ~specialwords.models.types.OrModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3053,11 +3110,13 @@ def with_pass(self, body: _models1.PassModel, *, content_type: str = "applicatio """ @overload - def with_pass(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_pass( + self, body: _types_models1.PassModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_pass. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.PassModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3081,12 +3140,13 @@ def with_pass(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_pass( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.PassModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.PassModel, _types_models1.PassModel, IO[bytes]], **kwargs: Any ) -> None: """with_pass. - :param body: Is one of the following types: PassModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.PassModel or JSON or IO[bytes] + :param body: Is either a PassModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.PassModel or ~specialwords.models.types.PassModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3150,11 +3210,13 @@ def with_raise(self, body: _models1.RaiseModel, *, content_type: str = "applicat """ @overload - def with_raise(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_raise( + self, body: _types_models1.RaiseModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_raise. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.RaiseModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3178,12 +3240,13 @@ def with_raise(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_raise( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.RaiseModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.RaiseModel, _types_models1.RaiseModel, IO[bytes]], **kwargs: Any ) -> None: """with_raise. - :param body: Is one of the following types: RaiseModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.RaiseModel or JSON or IO[bytes] + :param body: Is either a RaiseModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.RaiseModel or ~specialwords.models.types.RaiseModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3247,11 +3310,13 @@ def with_return(self, body: _models1.ReturnModel, *, content_type: str = "applic """ @overload - def with_return(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_return( + self, body: _types_models1.ReturnModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_return. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.ReturnModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3275,12 +3340,13 @@ def with_return(self, body: IO[bytes], *, content_type: str = "application/json" """ def with_return( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.ReturnModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.ReturnModel, _types_models1.ReturnModel, IO[bytes]], **kwargs: Any ) -> None: """with_return. - :param body: Is one of the following types: ReturnModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.ReturnModel or JSON or IO[bytes] + :param body: Is either a ReturnModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.ReturnModel or ~specialwords.models.types.ReturnModel + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3344,11 +3410,11 @@ def with_try(self, body: _models1.TryModel, *, content_type: str = "application/ """ @overload - def with_try(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_try(self, body: _types_models1.TryModel, *, content_type: str = "application/json", **kwargs: Any) -> None: """with_try. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.TryModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3372,12 +3438,13 @@ def with_try(self, body: IO[bytes], *, content_type: str = "application/json", * """ def with_try( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.TryModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.TryModel, _types_models1.TryModel, IO[bytes]], **kwargs: Any ) -> None: """with_try. - :param body: Is one of the following types: TryModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.TryModel or JSON or IO[bytes] + :param body: Is either a TryModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.TryModel or ~specialwords.models.types.TryModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3441,11 +3508,13 @@ def with_while(self, body: _models1.WhileModel, *, content_type: str = "applicat """ @overload - def with_while(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_while( + self, body: _types_models1.WhileModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_while. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.WhileModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3469,12 +3538,13 @@ def with_while(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_while( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.WhileModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.WhileModel, _types_models1.WhileModel, IO[bytes]], **kwargs: Any ) -> None: """with_while. - :param body: Is one of the following types: WhileModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.WhileModel or JSON or IO[bytes] + :param body: Is either a WhileModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.WhileModel or ~specialwords.models.types.WhileModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3538,11 +3608,13 @@ def with_with(self, body: _models1.WithModel, *, content_type: str = "applicatio """ @overload - def with_with(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_with( + self, body: _types_models1.WithModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_with. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.WithModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3566,12 +3638,13 @@ def with_with(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_with( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.WithModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.WithModel, _types_models1.WithModel, IO[bytes]], **kwargs: Any ) -> None: """with_with. - :param body: Is one of the following types: WithModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.WithModel or JSON or IO[bytes] + :param body: Is either a WithModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.WithModel or ~specialwords.models.types.WithModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3635,11 +3708,13 @@ def with_yield(self, body: _models1.YieldModel, *, content_type: str = "applicat """ @overload - def with_yield(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_yield( + self, body: _types_models1.YieldModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_yield. :param body: Required. - :type body: JSON + :type body: ~specialwords.models.types.YieldModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3663,12 +3738,13 @@ def with_yield(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_yield( # pylint: disable=inconsistent-return-statements - self, body: Union[_models1.YieldModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models1.YieldModel, _types_models1.YieldModel, IO[bytes]], **kwargs: Any ) -> None: """with_yield. - :param body: Is one of the following types: YieldModel, JSON, IO[bytes] Required. - :type body: ~specialwords.models.models.YieldModel or JSON or IO[bytes] + :param body: Is either a YieldModel type or a IO[bytes] type. Required. + :type body: ~specialwords.models.models.YieldModel or ~specialwords.models.types.YieldModel or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/models/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/aio/operations/_operations.py index 85626fb6e83f..72aaa2a2d614 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/aio/operations/_operations.py @@ -17,6 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict +from ... import types as _types_models2 from ...._utils.model_base import SdkJSONEncoder from ...._utils.serialization import Deserializer, Serializer from ....aio._configuration import SpecialWordsClientConfiguration @@ -60,11 +61,13 @@ async def with_items(self, *, items: list[str], content_type: str = "application """ @overload - async def with_items(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def with_items( + self, body: _types_models2.WithItemsRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_items. :param body: Required. - :type body: JSON + :type body: ~specialwords.reservedoperationbodyparams.types.WithItemsRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -88,12 +91,17 @@ async def with_items(self, body: IO[bytes], *, content_type: str = "application/ """ async def with_items( - self, body: Union[JSON, IO[bytes]] = _Unset, *, items: list[str] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types_models2.WithItemsRequest, IO[bytes]] = _Unset, + *, + items: list[str] = _Unset, + **kwargs: Any ) -> None: """with_items. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, WithItemsRequest, IO[bytes] Required. + :type body: JSON or ~specialwords.reservedoperationbodyparams.types.WithItemsRequest or + IO[bytes] :keyword items: Required. :paramtype items: list[str] :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/aio/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/aio/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/models/__init__.py new file mode 100644 index 000000000000..e895c08ad4bc --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/models/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/models/_patch.py new file mode 100644 index 000000000000..bbe39eaf695d --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/models/_patch.py @@ -0,0 +1,18 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/operations/_operations.py index c9dd676de58a..4ec6ab5cc4e4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/operations/_operations.py @@ -17,6 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict +from .. import types as _types_models1 from ..._configuration import SpecialWordsClientConfiguration from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer @@ -78,11 +79,13 @@ def with_items(self, *, items: list[str], content_type: str = "application/json" """ @overload - def with_items(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def with_items( + self, body: _types_models1.WithItemsRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """with_items. :param body: Required. - :type body: JSON + :type body: ~specialwords.reservedoperationbodyparams.types.WithItemsRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -106,12 +109,17 @@ def with_items(self, body: IO[bytes], *, content_type: str = "application/json", """ def with_items( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, items: list[str] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types_models1.WithItemsRequest, IO[bytes]] = _Unset, + *, + items: list[str] = _Unset, + **kwargs: Any, ) -> None: """with_items. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, WithItemsRequest, IO[bytes] Required. + :type body: JSON or ~specialwords.reservedoperationbodyparams.types.WithItemsRequest or + IO[bytes] :keyword items: Required. :paramtype items: list[str] :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/types.py new file mode 100644 index 000000000000..730c8cf46d2e --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/special-words/specialwords/reservedoperationbodyparams/types.py @@ -0,0 +1,14 @@ +# coding=utf-8 + +from typing_extensions import Required, TypedDict + + +class WithItemsRequest(TypedDict, total=False): + """WithItemsRequest. + + :ivar items_property: Required. + :vartype items_property: list[str] + """ + + items: Required[list[str]] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/pyproject.toml index 5bf059ca3c74..d80f16a5615e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/operations/_operations.py index f6bffb6bd739..93f038b6e262 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/operations/_operations.py @@ -17,7 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -127,11 +127,13 @@ async def bullet_points_model( """ @overload - async def bullet_points_model(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def bullet_points_model( + self, body: _types.BulletPointsModelRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """bullet_points_model. :param body: Required. - :type body: JSON + :type body: ~specs.documentation.types.BulletPointsModelRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -157,12 +159,16 @@ async def bullet_points_model( """ async def bullet_points_model( - self, body: Union[JSON, IO[bytes]] = _Unset, *, input: _models.BulletPointsModel = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.BulletPointsModelRequest, IO[bytes]] = _Unset, + *, + input: _models.BulletPointsModel = _Unset, + **kwargs: Any ) -> None: """bullet_points_model. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BulletPointsModelRequest, IO[bytes] Required. + :type body: JSON or ~specs.documentation.types.BulletPointsModelRequest or IO[bytes] :keyword input: Required. :paramtype input: ~specs.documentation.models.BulletPointsModel :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/aio/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/models/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/models/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/operations/_operations.py index a514afc00dbc..7a7268bd739e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/operations/_operations.py @@ -17,7 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import DocumentationClientConfiguration from .._utils.model_base import SdkJSONEncoder from .._utils.serialization import Deserializer, Serializer @@ -171,11 +171,13 @@ def bullet_points_model( """ @overload - def bullet_points_model(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def bullet_points_model( + self, body: _types.BulletPointsModelRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """bullet_points_model. :param body: Required. - :type body: JSON + :type body: ~specs.documentation.types.BulletPointsModelRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -199,12 +201,16 @@ def bullet_points_model(self, body: IO[bytes], *, content_type: str = "applicati """ def bullet_points_model( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, input: _models.BulletPointsModel = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.BulletPointsModelRequest, IO[bytes]] = _Unset, + *, + input: _models.BulletPointsModel = _Unset, + **kwargs: Any ) -> None: """bullet_points_model. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, BulletPointsModelRequest, IO[bytes] Required. + :type body: JSON or ~specs.documentation.types.BulletPointsModelRequest or IO[bytes] :keyword input: Required. :paramtype input: ~specs.documentation.models.BulletPointsModel :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/types.py index 1a5fba439634..96858d44d202 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/specs-documentation/specs/documentation/types.py @@ -40,7 +40,7 @@ class BulletPointsModel(TypedDict, total=False): both bold and italic formatting and is long enough to test the wrapping behavior in such cases. * **Bold bullet point** * *Italic bullet point*. Required. Known values are: "Simple", "Bold", and "Italic". - :vartype prop: str or ~specs.documentation.models.BulletPointsEnum + :vartype prop: Union[str, "BulletPointsEnum"] """ prop: Required[Union[str, "BulletPointsEnum"]] @@ -58,3 +58,14 @@ class BulletPointsModel(TypedDict, total=False): both bold and italic formatting and is long enough to test the wrapping behavior in such cases. * **Bold bullet point** * *Italic bullet point*. Required. Known values are: \"Simple\", \"Bold\", and \"Italic\".""" + + +class BulletPointsModelRequest(TypedDict, total=False): + """BulletPointsModelRequest. + + :ivar input: Required. + :vartype input: "BulletPointsModel" + """ + + input: Required["BulletPointsModel"] + """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/pyproject.toml index 7232bd6ddd46..e02b38ac58db 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/models/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/models/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/types.py deleted file mode 100644 index 05e5587390c8..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/streaming-jsonl/streaming/jsonl/basic/types.py +++ /dev/null @@ -1,14 +0,0 @@ -# coding=utf-8 - -from typing_extensions import Required, TypedDict - - -class Info(TypedDict, total=False): - """Info. - - :ivar desc: Required. - :vartype desc: str - """ - - desc: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/pyproject.toml index e083038c87ca..7f3554d6e6d6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/operations/_operations.py index e314533e36db..3ad3be2cfca7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/operations/_operations.py @@ -21,7 +21,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -58,7 +58,6 @@ T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] class Int32ValueOperations: @@ -1377,11 +1376,13 @@ async def put( """ @overload - async def put(self, body: list[JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: list[_types.InnerModel], *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put. :param body: Required. - :type body: list[JSON] + :type body: list[~typetest.array.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1404,11 +1405,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[list[_models.InnerModel], list[JSON], IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[list[_models.InnerModel], list[_types.InnerModel], IO[bytes]], **kwargs: Any + ) -> None: """put. - :param body: Is one of the following types: [InnerModel], [JSON], IO[bytes] Required. - :type body: list[~typetest.array.models.InnerModel] or list[JSON] or IO[bytes] + :param body: Is either a [InnerModel] type or a IO[bytes] type. Required. + :type body: list[~typetest.array.models.InnerModel] or list[~typetest.array.types.InnerModel] + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2158,11 +2162,13 @@ async def put( """ @overload - async def put(self, body: list[JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: list[_types.InnerModel], *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put. :param body: Required. - :type body: list[JSON] + :type body: list[~typetest.array.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2185,11 +2191,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[list[_models.InnerModel], list[JSON], IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[list[_models.InnerModel], list[_types.InnerModel], IO[bytes]], **kwargs: Any + ) -> None: """put. - :param body: Is one of the following types: [InnerModel], [JSON], IO[bytes] Required. - :type body: list[~typetest.array.models.InnerModel] or list[JSON] or IO[bytes] + :param body: Is either a [InnerModel] type or a IO[bytes] type. Required. + :type body: list[~typetest.array.models.InnerModel] or list[~typetest.array.types.InnerModel] + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/operations/_operations.py index a6afe49384b7..33765ea35d43 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/operations/_operations.py @@ -21,14 +21,13 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import ArrayClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -1752,11 +1751,11 @@ def put(self, body: list[_models.InnerModel], *, content_type: str = "applicatio """ @overload - def put(self, body: list[JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: list[_types.InnerModel], *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param body: Required. - :type body: list[JSON] + :type body: list[~typetest.array.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1780,12 +1779,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[list[_models.InnerModel], list[JSON], IO[bytes]], **kwargs: Any + self, body: Union[list[_models.InnerModel], list[_types.InnerModel], IO[bytes]], **kwargs: Any ) -> None: """put. - :param body: Is one of the following types: [InnerModel], [JSON], IO[bytes] Required. - :type body: list[~typetest.array.models.InnerModel] or list[JSON] or IO[bytes] + :param body: Is either a [InnerModel] type or a IO[bytes] type. Required. + :type body: list[~typetest.array.models.InnerModel] or list[~typetest.array.types.InnerModel] + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2541,11 +2541,11 @@ def put(self, body: list[_models.InnerModel], *, content_type: str = "applicatio """ @overload - def put(self, body: list[JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: list[_types.InnerModel], *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param body: Required. - :type body: list[JSON] + :type body: list[~typetest.array.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2569,12 +2569,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[list[_models.InnerModel], list[JSON], IO[bytes]], **kwargs: Any + self, body: Union[list[_models.InnerModel], list[_types.InnerModel], IO[bytes]], **kwargs: Any ) -> None: """put. - :param body: Is one of the following types: [InnerModel], [JSON], IO[bytes] Required. - :type body: list[~typetest.array.models.InnerModel] or list[JSON] or IO[bytes] + :param body: Is either a [InnerModel] type or a IO[bytes] type. Required. + :type body: list[~typetest.array.models.InnerModel] or list[~typetest.array.types.InnerModel] + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/types.py index c28b9c11a435..98713723ba26 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-array/typetest/array/types.py @@ -9,7 +9,7 @@ class InnerModel(TypedDict, total=False): :ivar property: Required string property. Required. :vartype property: str :ivar children: - :vartype children: list[~typetest.array.models.InnerModel] + :vartype children: list["InnerModel"] """ property: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/pyproject.toml index ba82dee20607..ed35975f9dc6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/operations/_operations.py index 923eadb60fa1..061bd09e735d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/operations/_operations.py @@ -21,7 +21,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -52,7 +52,6 @@ T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] class Int32ValueOperations: @@ -1371,11 +1370,13 @@ async def put( """ @overload - async def put(self, body: dict[str, JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: dict[str, _types.InnerModel], *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put. :param body: Required. - :type body: dict[str, JSON] + :type body: dict[str, ~typetest.dictionary.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1398,11 +1399,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[dict[str, _models.InnerModel], dict[str, JSON], IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[dict[str, _models.InnerModel], dict[str, _types.InnerModel], IO[bytes]], **kwargs: Any + ) -> None: """put. - :param body: Is one of the following types: {str: InnerModel}, {str: JSON}, IO[bytes] Required. - :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, JSON] or IO[bytes] + :param body: Is either a {str: InnerModel} type or a IO[bytes] type. Required. + :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, + ~typetest.dictionary.types.InnerModel] or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1540,11 +1544,13 @@ async def put( """ @overload - async def put(self, body: dict[str, JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: dict[str, _types.InnerModel], *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put. :param body: Required. - :type body: dict[str, JSON] + :type body: dict[str, ~typetest.dictionary.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1567,11 +1573,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[dict[str, _models.InnerModel], dict[str, JSON], IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[dict[str, _models.InnerModel], dict[str, _types.InnerModel], IO[bytes]], **kwargs: Any + ) -> None: """put. - :param body: Is one of the following types: {str: InnerModel}, {str: JSON}, IO[bytes] Required. - :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, JSON] or IO[bytes] + :param body: Is either a {str: InnerModel} type or a IO[bytes] type. Required. + :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, + ~typetest.dictionary.types.InnerModel] or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/operations/_operations.py index fd018ecbe347..e9978c3c4305 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/operations/_operations.py @@ -21,14 +21,13 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import DictionaryClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -1672,11 +1671,11 @@ def put( """ @overload - def put(self, body: dict[str, JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: dict[str, _types.InnerModel], *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param body: Required. - :type body: dict[str, JSON] + :type body: dict[str, ~typetest.dictionary.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1700,12 +1699,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[dict[str, _models.InnerModel], dict[str, JSON], IO[bytes]], **kwargs: Any + self, body: Union[dict[str, _models.InnerModel], dict[str, _types.InnerModel], IO[bytes]], **kwargs: Any ) -> None: """put. - :param body: Is one of the following types: {str: InnerModel}, {str: JSON}, IO[bytes] Required. - :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, JSON] or IO[bytes] + :param body: Is either a {str: InnerModel} type or a IO[bytes] type. Required. + :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, + ~typetest.dictionary.types.InnerModel] or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1843,11 +1843,11 @@ def put( """ @overload - def put(self, body: dict[str, JSON], *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: dict[str, _types.InnerModel], *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param body: Required. - :type body: dict[str, JSON] + :type body: dict[str, ~typetest.dictionary.types.InnerModel] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1871,12 +1871,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[dict[str, _models.InnerModel], dict[str, JSON], IO[bytes]], **kwargs: Any + self, body: Union[dict[str, _models.InnerModel], dict[str, _types.InnerModel], IO[bytes]], **kwargs: Any ) -> None: """put. - :param body: Is one of the following types: {str: InnerModel}, {str: JSON}, IO[bytes] Required. - :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, JSON] or IO[bytes] + :param body: Is either a {str: InnerModel} type or a IO[bytes] type. Required. + :type body: dict[str, ~typetest.dictionary.models.InnerModel] or dict[str, + ~typetest.dictionary.types.InnerModel] or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/types.py index 6427fa5aface..01f98dedb0d1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-dictionary/typetest/dictionary/types.py @@ -9,7 +9,7 @@ class InnerModel(TypedDict, total=False): :ivar property: Required string property. Required. :vartype property: str :ivar children: - :vartype children: dict[str, ~typetest.dictionary.models.InnerModel] + :vartype children: dict[str, "InnerModel"] """ property: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/pyproject.toml index b381e57d24ea..2df32d5aa924 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_types.py deleted file mode 100644 index 04525bdc89cb..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_types.py +++ /dev/null @@ -1,10 +0,0 @@ -# coding=utf-8 - -from typing import TYPE_CHECKING, Union - -if TYPE_CHECKING: - from . import models as _models -PetWithEnvelope = Union["_models.Cat", "_models.Dog"] -PetWithCustomNames = Union["_models.Cat", "_models.Dog"] -PetInline = Union["_models.Cat", "_models.Dog"] -PetInlineWithCustomDiscriminator = Union["_models.Cat", "_models.Dog"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_operations.py index 48fffd791b3e..c6424e1dd8d6 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_operations.py @@ -34,7 +34,7 @@ from .._configuration import DiscriminatedClientConfiguration if TYPE_CHECKING: - from ... import _types + from ... import _unions T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -122,7 +122,7 @@ def __init__(self, *args, **kwargs) -> None: self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetInline": + async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_unions.PetInline": """get. :keyword kind: Default value is None. @@ -142,7 +142,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetInline"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInline"] = kwargs.pop("cls", None) _request = build_no_envelope_default_get_request( kind=kind, @@ -172,7 +172,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInline", response.json()) + deserialized = _deserialize("_unions.PetInline", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -182,7 +182,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet @overload async def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInline": + ) -> "_unions.PetInline": """put. :param input: Required. @@ -198,7 +198,7 @@ async def put( @overload async def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInline": + ) -> "_unions.PetInline": """put. :param input: Required. @@ -211,7 +211,7 @@ async def put( :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInline": + async def put(self, input: "_unions.PetInline", **kwargs: Any) -> "_unions.PetInline": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -232,7 +232,7 @@ async def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInli _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetInline"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInline"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -266,7 +266,7 @@ async def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInli if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInline", response.json()) + deserialized = _deserialize("_unions.PetInline", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -291,7 +291,7 @@ def __init__(self, *args, **kwargs) -> None: self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.PetInlineWithCustomDiscriminator": + async def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_unions.PetInlineWithCustomDiscriminator": """get. :keyword type: Default value is None. @@ -311,7 +311,7 @@ async def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.Pet _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) _request = build_no_envelope_custom_discriminator_get_request( type=type, @@ -341,7 +341,7 @@ async def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.Pet if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInlineWithCustomDiscriminator", response.json()) + deserialized = _deserialize("_unions.PetInlineWithCustomDiscriminator", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -351,7 +351,7 @@ async def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.Pet @overload async def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Required. @@ -367,7 +367,7 @@ async def put( @overload async def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Required. @@ -381,8 +381,8 @@ async def put( """ async def put( - self, input: "_types.PetInlineWithCustomDiscriminator", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + self, input: "_unions.PetInlineWithCustomDiscriminator", **kwargs: Any + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -403,7 +403,7 @@ async def put( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -437,7 +437,7 @@ async def put( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInlineWithCustomDiscriminator", response.json()) + deserialized = _deserialize("_unions.PetInlineWithCustomDiscriminator", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -462,7 +462,7 @@ def __init__(self, *args, **kwargs) -> None: self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetWithEnvelope": + async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_unions.PetWithEnvelope": """get. :keyword kind: Default value is None. @@ -482,7 +482,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetWithEnvelope"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithEnvelope"] = kwargs.pop("cls", None) _request = build_envelope_object_default_get_request( kind=kind, @@ -512,7 +512,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithEnvelope", response.json()) + deserialized = _deserialize("_unions.PetWithEnvelope", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -522,7 +522,7 @@ async def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.Pet @overload async def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithEnvelope": + ) -> "_unions.PetWithEnvelope": """put. :param input: Required. @@ -538,7 +538,7 @@ async def put( @overload async def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithEnvelope": + ) -> "_unions.PetWithEnvelope": """put. :param input: Required. @@ -551,7 +551,7 @@ async def put( :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.PetWithEnvelope": + async def put(self, input: "_unions.PetWithEnvelope", **kwargs: Any) -> "_unions.PetWithEnvelope": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -572,7 +572,7 @@ async def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.P _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetWithEnvelope"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithEnvelope"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -606,7 +606,7 @@ async def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.P if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithEnvelope", response.json()) + deserialized = _deserialize("_unions.PetWithEnvelope", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -631,7 +631,7 @@ def __init__(self, *args, **kwargs) -> None: self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types.PetWithCustomNames": + async def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_unions.PetWithCustomNames": """get. :keyword pet_type: Default value is None. @@ -651,7 +651,7 @@ async def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetWithCustomNames"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithCustomNames"] = kwargs.pop("cls", None) _request = build_envelope_object_custom_properties_get_request( pet_type=pet_type, @@ -681,7 +681,7 @@ async def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithCustomNames", response.json()) + deserialized = _deserialize("_unions.PetWithCustomNames", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -691,7 +691,7 @@ async def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types @overload async def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithCustomNames": + ) -> "_unions.PetWithCustomNames": """put. :param input: Required. @@ -707,7 +707,7 @@ async def put( @overload async def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithCustomNames": + ) -> "_unions.PetWithCustomNames": """put. :param input: Required. @@ -720,7 +720,7 @@ async def put( :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_types.PetWithCustomNames": + async def put(self, input: "_unions.PetWithCustomNames", **kwargs: Any) -> "_unions.PetWithCustomNames": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -741,7 +741,7 @@ async def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_type _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetWithCustomNames"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithCustomNames"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -775,7 +775,7 @@ async def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_type if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithCustomNames", response.json()) + deserialized = _deserialize("_unions.PetWithCustomNames", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/aio/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/models/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/models/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/operations/_operations.py index 656a36d6f751..69a5350ce796 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/operations/_operations.py @@ -24,7 +24,7 @@ from .._utils.serialization import Deserializer, Serializer if TYPE_CHECKING: - from .. import _types + from .. import _unions T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -265,7 +265,7 @@ def __init__(self, *args, **kwargs) -> None: self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetInline": + def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_unions.PetInline": """get. :keyword kind: Default value is None. @@ -285,7 +285,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetInline _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetInline"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInline"] = kwargs.pop("cls", None) _request = build_no_envelope_default_get_request( kind=kind, @@ -315,7 +315,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetInline if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInline", response.json()) + deserialized = _deserialize("_unions.PetInline", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -323,7 +323,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetInline return deserialized # type: ignore @overload - def put(self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any) -> "_types.PetInline": + def put(self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any) -> "_unions.PetInline": """put. :param input: Required. @@ -337,7 +337,7 @@ def put(self, input: _models.Cat, *, content_type: str = "application/json", **k """ @overload - def put(self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any) -> "_types.PetInline": + def put(self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any) -> "_unions.PetInline": """put. :param input: Required. @@ -350,7 +350,7 @@ def put(self, input: _models.Dog, *, content_type: str = "application/json", **k :raises ~corehttp.exceptions.HttpResponseError: """ - def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInline": + def put(self, input: "_unions.PetInline", **kwargs: Any) -> "_unions.PetInline": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -371,7 +371,7 @@ def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInline": _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetInline"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInline"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -405,7 +405,7 @@ def put(self, input: "_types.PetInline", **kwargs: Any) -> "_types.PetInline": if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInline", response.json()) + deserialized = _deserialize("_unions.PetInline", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -430,7 +430,7 @@ def __init__(self, *args, **kwargs) -> None: self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.PetInlineWithCustomDiscriminator": + def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_unions.PetInlineWithCustomDiscriminator": """get. :keyword type: Default value is None. @@ -450,7 +450,7 @@ def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.PetInline _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) _request = build_no_envelope_custom_discriminator_get_request( type=type, @@ -480,7 +480,7 @@ def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.PetInline if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInlineWithCustomDiscriminator", response.json()) + deserialized = _deserialize("_unions.PetInlineWithCustomDiscriminator", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -490,7 +490,7 @@ def get(self, *, type: Optional[str] = None, **kwargs: Any) -> "_types.PetInline @overload def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Required. @@ -506,7 +506,7 @@ def put( @overload def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Required. @@ -520,8 +520,8 @@ def put( """ def put( - self, input: "_types.PetInlineWithCustomDiscriminator", **kwargs: Any - ) -> "_types.PetInlineWithCustomDiscriminator": + self, input: "_unions.PetInlineWithCustomDiscriminator", **kwargs: Any + ) -> "_unions.PetInlineWithCustomDiscriminator": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -542,7 +542,7 @@ def put( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetInlineWithCustomDiscriminator"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -576,7 +576,7 @@ def put( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetInlineWithCustomDiscriminator", response.json()) + deserialized = _deserialize("_unions.PetInlineWithCustomDiscriminator", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -601,7 +601,7 @@ def __init__(self, *args, **kwargs) -> None: self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetWithEnvelope": + def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_unions.PetWithEnvelope": """get. :keyword kind: Default value is None. @@ -621,7 +621,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetWithEn _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetWithEnvelope"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithEnvelope"] = kwargs.pop("cls", None) _request = build_envelope_object_default_get_request( kind=kind, @@ -651,7 +651,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetWithEn if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithEnvelope", response.json()) + deserialized = _deserialize("_unions.PetWithEnvelope", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -661,7 +661,7 @@ def get(self, *, kind: Optional[str] = None, **kwargs: Any) -> "_types.PetWithEn @overload def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithEnvelope": + ) -> "_unions.PetWithEnvelope": """put. :param input: Required. @@ -677,7 +677,7 @@ def put( @overload def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithEnvelope": + ) -> "_unions.PetWithEnvelope": """put. :param input: Required. @@ -690,7 +690,7 @@ def put( :raises ~corehttp.exceptions.HttpResponseError: """ - def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.PetWithEnvelope": + def put(self, input: "_unions.PetWithEnvelope", **kwargs: Any) -> "_unions.PetWithEnvelope": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -711,7 +711,7 @@ def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.PetWith _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetWithEnvelope"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithEnvelope"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -745,7 +745,7 @@ def put(self, input: "_types.PetWithEnvelope", **kwargs: Any) -> "_types.PetWith if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithEnvelope", response.json()) + deserialized = _deserialize("_unions.PetWithEnvelope", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -770,7 +770,7 @@ def __init__(self, *args, **kwargs) -> None: self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types.PetWithCustomNames": + def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_unions.PetWithCustomNames": """get. :keyword pet_type: Default value is None. @@ -790,7 +790,7 @@ def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types.PetWi _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType["_types.PetWithCustomNames"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithCustomNames"] = kwargs.pop("cls", None) _request = build_envelope_object_custom_properties_get_request( pet_type=pet_type, @@ -820,7 +820,7 @@ def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types.PetWi if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithCustomNames", response.json()) + deserialized = _deserialize("_unions.PetWithCustomNames", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -830,7 +830,7 @@ def get(self, *, pet_type: Optional[str] = None, **kwargs: Any) -> "_types.PetWi @overload def put( self, input: _models.Cat, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithCustomNames": + ) -> "_unions.PetWithCustomNames": """put. :param input: Required. @@ -846,7 +846,7 @@ def put( @overload def put( self, input: _models.Dog, *, content_type: str = "application/json", **kwargs: Any - ) -> "_types.PetWithCustomNames": + ) -> "_unions.PetWithCustomNames": """put. :param input: Required. @@ -859,7 +859,7 @@ def put( :raises ~corehttp.exceptions.HttpResponseError: """ - def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_types.PetWithCustomNames": + def put(self, input: "_unions.PetWithCustomNames", **kwargs: Any) -> "_unions.PetWithCustomNames": """put. :param input: Is either a Cat type or a Dog type. Required. @@ -880,7 +880,7 @@ def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_types.PetW _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType["_types.PetWithCustomNames"] = kwargs.pop("cls", None) + cls: ClsType["_unions.PetWithCustomNames"] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -914,7 +914,7 @@ def put(self, input: "_types.PetWithCustomNames", **kwargs: Any) -> "_types.PetW if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize("_types.PetWithCustomNames", response.json()) + deserialized = _deserialize("_unions.PetWithCustomNames", response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/operations/_patch.py index b208fb11fbc2..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/operations/_patch.py @@ -5,6 +5,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/types.py deleted file mode 100644 index 5a37a3833320..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-discriminatedunion/typetest/discriminatedunion/types.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 - -from typing_extensions import Required, TypedDict - - -class Cat(TypedDict, total=False): - """Cat. - - :ivar name: Required. - :vartype name: str - :ivar meow: Required. - :vartype meow: bool - """ - - name: Required[str] - """Required.""" - meow: Required[bool] - """Required.""" - - -class Dog(TypedDict, total=False): - """Dog. - - :ivar name: Required. - :vartype name: str - :ivar bark: Required. - :vartype bark: bool - """ - - name: Required[str] - """Required.""" - bark: Required[bool] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/pyproject.toml index 7ecff2ccf983..b056e87bc2d1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-extensible/typetest/enum/extensible/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/pyproject.toml index e7a4d7cc78db..dae8a59c5c4f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-enum-fixed/typetest/enum/fixed/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/pyproject.toml index 8865ac1ce5dd..44906db797b3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_operations/_operations.py index b09de911bdea..4a3cfffb1a40 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import EmptyClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -95,11 +94,11 @@ def put_empty(self, input: _models.EmptyInput, *, content_type: str = "applicati """ @overload - def put_empty(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_empty(self, input: _types.EmptyInput, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_empty. :param input: Required. - :type input: JSON + :type input: ~typetest.model.empty.types.EmptyInput :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -123,12 +122,13 @@ def put_empty(self, input: IO[bytes], *, content_type: str = "application/json", """ def put_empty( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.EmptyInput, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.EmptyInput, _types.EmptyInput, IO[bytes]], **kwargs: Any ) -> None: """put_empty. - :param input: Is one of the following types: EmptyInput, JSON, IO[bytes] Required. - :type input: ~typetest.model.empty.models.EmptyInput or JSON or IO[bytes] + :param input: Is either a EmptyInput type or a IO[bytes] type. Required. + :type input: ~typetest.model.empty.models.EmptyInput or ~typetest.model.empty.types.EmptyInput + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -249,12 +249,12 @@ def post_round_trip_empty( @overload def post_round_trip_empty( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.EmptyInputOutput, *, content_type: str = "application/json", **kwargs: Any ) -> _models.EmptyInputOutput: """post_round_trip_empty. :param body: Required. - :type body: JSON + :type body: ~typetest.model.empty.types.EmptyInputOutput :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -280,12 +280,13 @@ def post_round_trip_empty( """ def post_round_trip_empty( - self, body: Union[_models.EmptyInputOutput, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.EmptyInputOutput, _types.EmptyInputOutput, IO[bytes]], **kwargs: Any ) -> _models.EmptyInputOutput: """post_round_trip_empty. - :param body: Is one of the following types: EmptyInputOutput, JSON, IO[bytes] Required. - :type body: ~typetest.model.empty.models.EmptyInputOutput or JSON or IO[bytes] + :param body: Is either a EmptyInputOutput type or a IO[bytes] type. Required. + :type body: ~typetest.model.empty.models.EmptyInputOutput or + ~typetest.model.empty.types.EmptyInputOutput or IO[bytes] :return: EmptyInputOutput. The EmptyInputOutput is compatible with MutableMapping :rtype: ~typetest.model.empty.models.EmptyInputOutput :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_operations/_operations.py index 5061dacbf526..5ed0b1f17fe0 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_empty_get_empty_request, build_empty_post_round_trip_empty_request, @@ -29,7 +29,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import EmptyClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -55,11 +54,13 @@ async def put_empty( """ @overload - async def put_empty(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_empty( + self, input: _types.EmptyInput, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_empty. :param input: Required. - :type input: JSON + :type input: ~typetest.model.empty.types.EmptyInput :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -82,11 +83,12 @@ async def put_empty(self, input: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_empty(self, input: Union[_models.EmptyInput, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_empty(self, input: Union[_models.EmptyInput, _types.EmptyInput, IO[bytes]], **kwargs: Any) -> None: """put_empty. - :param input: Is one of the following types: EmptyInput, JSON, IO[bytes] Required. - :type input: ~typetest.model.empty.models.EmptyInput or JSON or IO[bytes] + :param input: Is either a EmptyInput type or a IO[bytes] type. Required. + :type input: ~typetest.model.empty.models.EmptyInput or ~typetest.model.empty.types.EmptyInput + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -211,12 +213,12 @@ async def post_round_trip_empty( @overload async def post_round_trip_empty( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.EmptyInputOutput, *, content_type: str = "application/json", **kwargs: Any ) -> _models.EmptyInputOutput: """post_round_trip_empty. :param body: Required. - :type body: JSON + :type body: ~typetest.model.empty.types.EmptyInputOutput :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -242,12 +244,13 @@ async def post_round_trip_empty( """ async def post_round_trip_empty( - self, body: Union[_models.EmptyInputOutput, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.EmptyInputOutput, _types.EmptyInputOutput, IO[bytes]], **kwargs: Any ) -> _models.EmptyInputOutput: """post_round_trip_empty. - :param body: Is one of the following types: EmptyInputOutput, JSON, IO[bytes] Required. - :type body: ~typetest.model.empty.models.EmptyInputOutput or JSON or IO[bytes] + :param body: Is either a EmptyInputOutput type or a IO[bytes] type. Required. + :type body: ~typetest.model.empty.models.EmptyInputOutput or + ~typetest.model.empty.types.EmptyInputOutput or IO[bytes] :return: EmptyInputOutput. The EmptyInputOutput is compatible with MutableMapping :rtype: ~typetest.model.empty.models.EmptyInputOutput :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/types.py index 1b65929ee31f..3c8591f8db0a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-empty/typetest/model/empty/types.py @@ -9,7 +9,3 @@ class EmptyInput(TypedDict, total=False): class EmptyInputOutput(TypedDict, total=False): """Empty model used in both parameter and return type.""" - - -class EmptyOutput(TypedDict, total=False): - """Empty model used in operation return type.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/pyproject.toml index 712344271a61..8238cd8a8569 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_operations.py index 7c6843382267..49db132ba346 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import EnumDiscriminatorClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -232,11 +231,11 @@ def put_extensible_model( """ @overload - def put_extensible_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_extensible_model(self, input: _types.Dog, *, content_type: str = "application/json", **kwargs: Any) -> None: """Send model with extensible enum discriminator type. :param input: Dog to create. Required. - :type input: JSON + :type input: ~typetest.model.enumdiscriminator.types.Dog :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -260,12 +259,13 @@ def put_extensible_model(self, input: IO[bytes], *, content_type: str = "applica """ def put_extensible_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Dog, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Dog, _types.Dog, IO[bytes]], **kwargs: Any ) -> None: """Send model with extensible enum discriminator type. - :param input: Dog to create. Is one of the following types: Dog, JSON, IO[bytes] Required. - :type input: ~typetest.model.enumdiscriminator.models.Dog or JSON or IO[bytes] + :param input: Dog to create. Is either a Dog type or a IO[bytes] type. Required. + :type input: ~typetest.model.enumdiscriminator.models.Dog or + ~typetest.model.enumdiscriminator.types.Dog or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -491,11 +491,11 @@ def put_fixed_model(self, input: _models.Snake, *, content_type: str = "applicat """ @overload - def put_fixed_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_fixed_model(self, input: _types.Snake, *, content_type: str = "application/json", **kwargs: Any) -> None: """Send model with fixed enum discriminator type. :param input: Snake to create. Required. - :type input: JSON + :type input: ~typetest.model.enumdiscriminator.types.Snake :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -519,12 +519,13 @@ def put_fixed_model(self, input: IO[bytes], *, content_type: str = "application/ """ def put_fixed_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Snake, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Snake, _types.Snake, IO[bytes]], **kwargs: Any ) -> None: """Send model with fixed enum discriminator type. - :param input: Snake to create. Is one of the following types: Snake, JSON, IO[bytes] Required. - :type input: ~typetest.model.enumdiscriminator.models.Snake or JSON or IO[bytes] + :param input: Snake to create. Is either a Snake type or a IO[bytes] type. Required. + :type input: ~typetest.model.enumdiscriminator.models.Snake or + ~typetest.model.enumdiscriminator.types.Snake or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_operations.py index bbdcff760464..f72e5bc34979 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_enum_discriminator_get_extensible_model_missing_discriminator_request, build_enum_discriminator_get_extensible_model_request, @@ -34,7 +34,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import EnumDiscriminatorClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -116,11 +115,13 @@ async def put_extensible_model( """ @overload - async def put_extensible_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_extensible_model( + self, input: _types.Dog, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Send model with extensible enum discriminator type. :param input: Dog to create. Required. - :type input: JSON + :type input: ~typetest.model.enumdiscriminator.types.Dog :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -145,11 +146,12 @@ async def put_extensible_model( :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_extensible_model(self, input: Union[_models.Dog, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_extensible_model(self, input: Union[_models.Dog, _types.Dog, IO[bytes]], **kwargs: Any) -> None: """Send model with extensible enum discriminator type. - :param input: Dog to create. Is one of the following types: Dog, JSON, IO[bytes] Required. - :type input: ~typetest.model.enumdiscriminator.models.Dog or JSON or IO[bytes] + :param input: Dog to create. Is either a Dog type or a IO[bytes] type. Required. + :type input: ~typetest.model.enumdiscriminator.models.Dog or + ~typetest.model.enumdiscriminator.types.Dog or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -387,11 +389,13 @@ async def put_fixed_model( """ @overload - async def put_fixed_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_fixed_model( + self, input: _types.Snake, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Send model with fixed enum discriminator type. :param input: Snake to create. Required. - :type input: JSON + :type input: ~typetest.model.enumdiscriminator.types.Snake :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -414,11 +418,12 @@ async def put_fixed_model(self, input: IO[bytes], *, content_type: str = "applic :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_fixed_model(self, input: Union[_models.Snake, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_fixed_model(self, input: Union[_models.Snake, _types.Snake, IO[bytes]], **kwargs: Any) -> None: """Send model with fixed enum discriminator type. - :param input: Snake to create. Is one of the following types: Snake, JSON, IO[bytes] Required. - :type input: ~typetest.model.enumdiscriminator.models.Snake or JSON or IO[bytes] + :param input: Snake to create. Is either a Snake type or a IO[bytes] type. Required. + :type input: ~typetest.model.enumdiscriminator.models.Snake or + ~typetest.model.enumdiscriminator.types.Snake or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/types.py index 3f031d19c0ee..605605921a13 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-enumdiscriminator/typetest/model/enumdiscriminator/types.py @@ -12,7 +12,7 @@ class Cobra(TypedDict, total=False): :ivar length: Length of the snake. Required. :vartype length: int :ivar kind: discriminator property. Required. Species cobra. - :vartype kind: str or ~typetest.model.enumdiscriminator.models.COBRA + :vartype kind: Literal[SnakeKind.COBRA] """ length: Required[int] @@ -27,7 +27,7 @@ class Golden(TypedDict, total=False): :ivar weight: Weight of the dog. Required. :vartype weight: int :ivar kind: discriminator property. Required. Species golden. - :vartype kind: str or ~typetest.model.enumdiscriminator.models.GOLDEN + :vartype kind: Literal[DogKind.GOLDEN] """ weight: Required[int] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/pyproject.toml index e5dff82c64c0..1b05b500aa38 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_operations.py index 30a12e45c4d5..56d7a0191608 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import NestedDiscriminatorClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -198,11 +197,11 @@ def put_model(self, input: _models.Fish, *, content_type: str = "application/jso """ @overload - def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model(self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.nesteddiscriminator.types.Fish :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -226,12 +225,13 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", """ def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Fish, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any ) -> None: """put_model. - :param input: Is one of the following types: Fish, JSON, IO[bytes] Required. - :type input: ~typetest.model.nesteddiscriminator.models.Fish or JSON or IO[bytes] + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.nesteddiscriminator.models.Fish or + ~typetest.model.nesteddiscriminator.types.Fish or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -351,11 +351,11 @@ def put_recursive_model( """ @overload - def put_recursive_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_recursive_model(self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_recursive_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.nesteddiscriminator.types.Fish :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -379,12 +379,13 @@ def put_recursive_model(self, input: IO[bytes], *, content_type: str = "applicat """ def put_recursive_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Fish, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any ) -> None: """put_recursive_model. - :param input: Is one of the following types: Fish, JSON, IO[bytes] Required. - :type input: ~typetest.model.nesteddiscriminator.models.Fish or JSON or IO[bytes] + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.nesteddiscriminator.models.Fish or + ~typetest.model.nesteddiscriminator.types.Fish or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_operations.py index 7fb93583922e..3572266c556b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_nested_discriminator_get_missing_discriminator_request, build_nested_discriminator_get_model_request, @@ -32,7 +32,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import NestedDiscriminatorClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -112,11 +111,11 @@ async def put_model(self, input: _models.Fish, *, content_type: str = "applicati """ @overload - async def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model(self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.nesteddiscriminator.types.Fish :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -139,11 +138,12 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_model(self, input: Union[_models.Fish, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_model(self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any) -> None: """put_model. - :param input: Is one of the following types: Fish, JSON, IO[bytes] Required. - :type input: ~typetest.model.nesteddiscriminator.models.Fish or JSON or IO[bytes] + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.nesteddiscriminator.models.Fish or + ~typetest.model.nesteddiscriminator.types.Fish or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -267,11 +267,13 @@ async def put_recursive_model( """ @overload - async def put_recursive_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_recursive_model( + self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_recursive_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.nesteddiscriminator.types.Fish :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -296,11 +298,12 @@ async def put_recursive_model( :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_recursive_model(self, input: Union[_models.Fish, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_recursive_model(self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any) -> None: """put_recursive_model. - :param input: Is one of the following types: Fish, JSON, IO[bytes] Required. - :type input: ~typetest.model.nesteddiscriminator.models.Fish or JSON or IO[bytes] + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.nesteddiscriminator.models.Fish or + ~typetest.model.nesteddiscriminator.types.Fish or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/types.py index 92df64719526..f199a109c3ae 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-nesteddiscriminator/typetest/model/nesteddiscriminator/types.py @@ -10,9 +10,9 @@ class GoblinShark(TypedDict, total=False): :ivar age: Required. :vartype age: int :ivar kind: Required. Default value is "shark". - :vartype kind: str + :vartype kind: Literal["shark"] :ivar sharktype: Required. Default value is "goblin". - :vartype sharktype: str + :vartype sharktype: Literal["goblin"] """ age: Required[int] @@ -30,13 +30,13 @@ class Salmon(TypedDict, total=False): :ivar age: Required. :vartype age: int :ivar kind: Required. Default value is "salmon". - :vartype kind: str + :vartype kind: Literal["salmon"] :ivar friends: - :vartype friends: list[~typetest.model.nesteddiscriminator.models.Fish] + :vartype friends: list["Fish"] :ivar hate: - :vartype hate: dict[str, ~typetest.model.nesteddiscriminator.models.Fish] + :vartype hate: dict[str, "Fish"] :ivar partner: - :vartype partner: ~typetest.model.nesteddiscriminator.models.Fish + :vartype partner: "Fish" """ age: Required[int] @@ -54,9 +54,9 @@ class SawShark(TypedDict, total=False): :ivar age: Required. :vartype age: int :ivar kind: Required. Default value is "shark". - :vartype kind: str + :vartype kind: Literal["shark"] :ivar sharktype: Required. Default value is "saw". - :vartype sharktype: str + :vartype sharktype: Literal["saw"] """ age: Required[int] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/README.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/pyproject.toml index 1b1ea5f5c657..f50d58c51039 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_operations/_operations.py index 694795b1e03e..0bdba389e493 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models, types +from .. import models as _models, types as _types from .._configuration import NotDiscriminatedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer @@ -96,7 +96,7 @@ def post_valid(self, input: _models.Siamese, *, content_type: str = "application """ @overload - def post_valid(self, input: types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: + def post_valid(self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: """post_valid. :param input: Required. @@ -124,7 +124,7 @@ def post_valid(self, input: IO[bytes], *, content_type: str = "application/json" """ def post_valid( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Siamese, types.Siamese, IO[bytes]], **kwargs: Any + self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any ) -> None: """post_valid. @@ -251,7 +251,7 @@ def put_valid( @overload def put_valid( - self, input: types.Siamese, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Siamese: """put_valid. @@ -279,7 +279,7 @@ def put_valid(self, input: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - def put_valid(self, input: Union[_models.Siamese, types.Siamese, IO[bytes]], **kwargs: Any) -> _models.Siamese: + def put_valid(self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any) -> _models.Siamese: """put_valid. :param input: Is either a Siamese type or a IO[bytes] type. Required. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/aio/_operations/_operations.py index 5836e33e966a..0269f4bdd1ab 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated-typeddict/typetest/model/notdiscriminated/typeddict/aio/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models, types +from ... import models as _models, types as _types from ..._operations._operations import ( build_not_discriminated_get_valid_request, build_not_discriminated_post_valid_request, @@ -54,7 +54,7 @@ async def post_valid( """ @overload - async def post_valid(self, input: types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def post_valid(self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: """post_valid. :param input: Required. @@ -81,7 +81,7 @@ async def post_valid(self, input: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def post_valid(self, input: Union[_models.Siamese, types.Siamese, IO[bytes]], **kwargs: Any) -> None: + async def post_valid(self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any) -> None: """post_valid. :param input: Is either a Siamese type or a IO[bytes] type. Required. @@ -211,7 +211,7 @@ async def put_valid( @overload async def put_valid( - self, input: types.Siamese, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Siamese: """put_valid. @@ -242,7 +242,7 @@ async def put_valid( """ async def put_valid( - self, input: Union[_models.Siamese, types.Siamese, IO[bytes]], **kwargs: Any + self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any ) -> _models.Siamese: """put_valid. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/pyproject.toml index bcec7140bf09..3a83d7e241ce 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_operations.py index 57d0c32bed35..475342fda239 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import NotDiscriminatedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -97,11 +96,11 @@ def post_valid(self, input: _models.Siamese, *, content_type: str = "application """ @overload - def post_valid(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def post_valid(self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: """post_valid. :param input: Required. - :type input: JSON + :type input: ~typetest.model.notdiscriminated.types.Siamese :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -125,12 +124,13 @@ def post_valid(self, input: IO[bytes], *, content_type: str = "application/json" """ def post_valid( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Siamese, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any ) -> None: """post_valid. - :param input: Is one of the following types: Siamese, JSON, IO[bytes] Required. - :type input: ~typetest.model.notdiscriminated.models.Siamese or JSON or IO[bytes] + :param input: Is either a Siamese type or a IO[bytes] type. Required. + :type input: ~typetest.model.notdiscriminated.models.Siamese or + ~typetest.model.notdiscriminated.types.Siamese or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -250,11 +250,13 @@ def put_valid( """ @overload - def put_valid(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Siamese: + def put_valid( + self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Siamese: """put_valid. :param input: Required. - :type input: JSON + :type input: ~typetest.model.notdiscriminated.types.Siamese :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -277,11 +279,12 @@ def put_valid(self, input: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - def put_valid(self, input: Union[_models.Siamese, JSON, IO[bytes]], **kwargs: Any) -> _models.Siamese: + def put_valid(self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any) -> _models.Siamese: """put_valid. - :param input: Is one of the following types: Siamese, JSON, IO[bytes] Required. - :type input: ~typetest.model.notdiscriminated.models.Siamese or JSON or IO[bytes] + :param input: Is either a Siamese type or a IO[bytes] type. Required. + :type input: ~typetest.model.notdiscriminated.models.Siamese or + ~typetest.model.notdiscriminated.types.Siamese or IO[bytes] :return: Siamese. The Siamese is compatible with MutableMapping :rtype: ~typetest.model.notdiscriminated.models.Siamese :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_operations.py index 9464f9cfeb88..377871b597d5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_not_discriminated_get_valid_request, build_not_discriminated_post_valid_request, @@ -29,7 +29,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import NotDiscriminatedClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -55,11 +54,11 @@ async def post_valid( """ @overload - async def post_valid(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def post_valid(self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any) -> None: """post_valid. :param input: Required. - :type input: JSON + :type input: ~typetest.model.notdiscriminated.types.Siamese :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -82,11 +81,12 @@ async def post_valid(self, input: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def post_valid(self, input: Union[_models.Siamese, JSON, IO[bytes]], **kwargs: Any) -> None: + async def post_valid(self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any) -> None: """post_valid. - :param input: Is one of the following types: Siamese, JSON, IO[bytes] Required. - :type input: ~typetest.model.notdiscriminated.models.Siamese or JSON or IO[bytes] + :param input: Is either a Siamese type or a IO[bytes] type. Required. + :type input: ~typetest.model.notdiscriminated.models.Siamese or + ~typetest.model.notdiscriminated.types.Siamese or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -210,11 +210,13 @@ async def put_valid( """ @overload - async def put_valid(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Siamese: + async def put_valid( + self, input: _types.Siamese, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Siamese: """put_valid. :param input: Required. - :type input: JSON + :type input: ~typetest.model.notdiscriminated.types.Siamese :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -239,11 +241,14 @@ async def put_valid( :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_valid(self, input: Union[_models.Siamese, JSON, IO[bytes]], **kwargs: Any) -> _models.Siamese: + async def put_valid( + self, input: Union[_models.Siamese, _types.Siamese, IO[bytes]], **kwargs: Any + ) -> _models.Siamese: """put_valid. - :param input: Is one of the following types: Siamese, JSON, IO[bytes] Required. - :type input: ~typetest.model.notdiscriminated.models.Siamese or JSON or IO[bytes] + :param input: Is either a Siamese type or a IO[bytes] type. Required. + :type input: ~typetest.model.notdiscriminated.models.Siamese or + ~typetest.model.notdiscriminated.types.Siamese or IO[bytes] :return: Siamese. The Siamese is compatible with MutableMapping :rtype: ~typetest.model.notdiscriminated.models.Siamese :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-notdiscriminated/typetest/model/notdiscriminated/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/pyproject.toml index b5db0b394ef7..0db5fbd9b5c5 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_operations/_operations.py index d75ddb0996c7..ca6aada87d05 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import RecursiveClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -80,11 +79,11 @@ def put(self, input: _models.Extension, *, content_type: str = "application/json """ @overload - def put(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, input: _types.Extension, *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param input: Required. - :type input: JSON + :type input: ~typetest.model.recursive.types.Extension :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -108,12 +107,13 @@ def put(self, input: IO[bytes], *, content_type: str = "application/json", **kwa """ def put( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Extension, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Extension, _types.Extension, IO[bytes]], **kwargs: Any ) -> None: """put. - :param input: Is one of the following types: Extension, JSON, IO[bytes] Required. - :type input: ~typetest.model.recursive.models.Extension or JSON or IO[bytes] + :param input: Is either a Extension type or a IO[bytes] type. Required. + :type input: ~typetest.model.recursive.models.Extension or + ~typetest.model.recursive.types.Extension or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_operations/_operations.py index 16b2cf6b24b4..9c0933cc56b9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_recursive_get_request, build_recursive_put_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import RecursiveClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -49,11 +48,11 @@ async def put(self, input: _models.Extension, *, content_type: str = "applicatio """ @overload - async def put(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, input: _types.Extension, *, content_type: str = "application/json", **kwargs: Any) -> None: """put. :param input: Required. - :type input: JSON + :type input: ~typetest.model.recursive.types.Extension :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -76,11 +75,12 @@ async def put(self, input: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, input: Union[_models.Extension, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, input: Union[_models.Extension, _types.Extension, IO[bytes]], **kwargs: Any) -> None: """put. - :param input: Is one of the following types: Extension, JSON, IO[bytes] Required. - :type input: ~typetest.model.recursive.models.Extension or JSON or IO[bytes] + :param input: Is either a Extension type or a IO[bytes] type. Required. + :type input: ~typetest.model.recursive.models.Extension or + ~typetest.model.recursive.types.Extension or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/types.py index 7f404c784a5a..031fe0891b38 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-recursive/typetest/model/recursive/types.py @@ -7,7 +7,7 @@ class Element(TypedDict, total=False): """element. :ivar extension: - :vartype extension: list[~typetest.model.recursive.models.Extension] + :vartype extension: list["Extension"] """ extension: list["Extension"] @@ -17,7 +17,7 @@ class Extension(Element): """extension. :ivar extension: - :vartype extension: list[~typetest.model.recursive.models.Extension] + :vartype extension: list["Extension"] :ivar level: Required. :vartype level: int """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/README.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/pyproject.toml index 61d710b12457..1af5fe7168fd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_operations/_operations.py index 4a40025c84a7..63cbff418d3f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models, types +from .. import models as _models, types as _types from .._configuration import SingleDiscriminatorClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer @@ -138,6 +138,38 @@ def build_single_discriminator_get_legacy_model_request(**kwargs: Any) -> HttpRe return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) +def build_single_discriminator_get_no_subtypes_model_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/type/model/inheritance/single-discriminator/no-subtypes/model" + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_single_discriminator_put_no_subtypes_model_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/type/model/inheritance/single-discriminator/no-subtypes/model" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + class _SingleDiscriminatorClientOperationsMixin( ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SingleDiscriminatorClientConfiguration] ): @@ -211,7 +243,7 @@ def put_model(self, input: _models.Bird, *, content_type: str = "application/jso """ @overload - def put_model(self, input: types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. @@ -239,7 +271,7 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", """ def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Bird, types.Bird, IO[bytes]], **kwargs: Any + self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any ) -> None: """put_model. @@ -365,7 +397,7 @@ def put_recursive_model( """ @overload - def put_recursive_model(self, input: types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_recursive_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_recursive_model. :param input: Required. @@ -393,7 +425,7 @@ def put_recursive_model(self, input: IO[bytes], *, content_type: str = "applicat """ def put_recursive_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Bird, types.Bird, IO[bytes]], **kwargs: Any + self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any ) -> None: """put_recursive_model. @@ -609,3 +641,159 @@ def get_legacy_model(self, **kwargs: Any) -> _models.Dinosaur: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + def get_no_subtypes_model(self, **kwargs: Any) -> _models.Fish: + """get_no_subtypes_model. + + :return: Fish. The Fish is compatible with MutableMapping + :rtype: ~typetest.model.singlediscriminator.typeddict.models.Fish + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Fish] = kwargs.pop("cls", None) + + _request = build_single_discriminator_get_no_subtypes_model_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Fish, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def put_no_subtypes_model( + self, input: _models.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.typeddict.models.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def put_no_subtypes_model( + self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.typeddict.types.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def put_no_subtypes_model(self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def put_no_subtypes_model( # pylint: disable=inconsistent-return-statements + self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.typeddict.models.Fish or + ~typetest.model.singlediscriminator.typeddict.types.Fish or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(input, (IOBase, bytes)): + _content = input + else: + _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_single_discriminator_put_no_subtypes_model_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/aio/_operations/_operations.py index dfe40a148e9d..51cd14e93b34 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/aio/_operations/_operations.py @@ -19,14 +19,16 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models, types +from ... import models as _models, types as _types from ..._operations._operations import ( build_single_discriminator_get_legacy_model_request, build_single_discriminator_get_missing_discriminator_request, build_single_discriminator_get_model_request, + build_single_discriminator_get_no_subtypes_model_request, build_single_discriminator_get_recursive_model_request, build_single_discriminator_get_wrong_discriminator_request, build_single_discriminator_put_model_request, + build_single_discriminator_put_no_subtypes_model_request, build_single_discriminator_put_recursive_model_request, ) from ..._utils.model_base import SdkJSONEncoder, _deserialize @@ -112,7 +114,7 @@ async def put_model(self, input: _models.Bird, *, content_type: str = "applicati """ @overload - async def put_model(self, input: types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. @@ -139,7 +141,7 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_model(self, input: Union[_models.Bird, types.Bird, IO[bytes]], **kwargs: Any) -> None: + async def put_model(self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any) -> None: """put_model. :param input: Is either a Bird type or a IO[bytes] type. Required. @@ -269,7 +271,7 @@ async def put_recursive_model( @overload async def put_recursive_model( - self, input: types.Bird, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any ) -> None: """put_recursive_model. @@ -299,7 +301,7 @@ async def put_recursive_model( :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_recursive_model(self, input: Union[_models.Bird, types.Bird, IO[bytes]], **kwargs: Any) -> None: + async def put_recursive_model(self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any) -> None: """put_recursive_model. :param input: Is either a Bird type or a IO[bytes] type. Required. @@ -522,3 +524,163 @@ async def get_legacy_model(self, **kwargs: Any) -> _models.Dinosaur: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + async def get_no_subtypes_model(self, **kwargs: Any) -> _models.Fish: + """get_no_subtypes_model. + + :return: Fish. The Fish is compatible with MutableMapping + :rtype: ~typetest.model.singlediscriminator.typeddict.models.Fish + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Fish] = kwargs.pop("cls", None) + + _request = build_single_discriminator_get_no_subtypes_model_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run( # type: ignore + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Fish, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def put_no_subtypes_model( + self, input: _models.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.typeddict.models.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def put_no_subtypes_model( + self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.typeddict.types.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def put_no_subtypes_model( + self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def put_no_subtypes_model(self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any) -> None: + """put_no_subtypes_model. + + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.typeddict.models.Fish or + ~typetest.model.singlediscriminator.typeddict.types.Fish or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(input, (IOBase, bytes)): + _content = input + else: + _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_single_discriminator_put_no_subtypes_model_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run( # type: ignore + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/__init__.py index 04145d222153..fa5b9ccbc703 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/__init__.py @@ -11,6 +11,7 @@ Bird, Dinosaur, Eagle, + Fish, Goose, SeaGull, Sparrow, @@ -24,6 +25,7 @@ "Bird", "Dinosaur", "Eagle", + "Fish", "Goose", "SeaGull", "Sparrow", diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/_models.py index 537f1ea60aa1..7b4553c02cc7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/models/_models.py @@ -129,6 +129,39 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.kind = "eagle" # type: ignore +class Fish(_Model): + """A discriminated model with no defined subtypes. The discriminator is declared but no models + extend it. + + :ivar kind: Required. + :vartype kind: str + :ivar size: Required. + :vartype size: int + """ + + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + size: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + size: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class Goose(Bird, discriminator="goose"): """The second level model in polymorphic single level inheritance. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/types.py index 318c4376bb55..59547a197b36 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator-typeddict/typetest/model/singlediscriminator/typeddict/types.py @@ -11,13 +11,13 @@ class Eagle(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "eagle". - :vartype kind: str + :vartype kind: Literal["eagle"] :ivar friends: - :vartype friends: list[~typetest.model.singlediscriminator.typeddict.models.Bird] + :vartype friends: list["Bird"] :ivar hate: - :vartype hate: dict[str, ~typetest.model.singlediscriminator.typeddict.models.Bird] + :vartype hate: dict[str, "Bird"] :ivar partner: - :vartype partner: ~typetest.model.singlediscriminator.typeddict.models.Bird + :vartype partner: "Bird" """ wingspan: Required[int] @@ -29,13 +29,29 @@ class Eagle(TypedDict, total=False): partner: "Bird" +class Fish(TypedDict, total=False): + """A discriminated model with no defined subtypes. The discriminator is declared but no models + extend it. + + :ivar kind: Required. + :vartype kind: str + :ivar size: Required. + :vartype size: int + """ + + kind: Required[str] + """Required.""" + size: Required[int] + """Required.""" + + class Goose(TypedDict, total=False): """The second level model in polymorphic single level inheritance. :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "goose". - :vartype kind: str + :vartype kind: Literal["goose"] """ wingspan: Required[int] @@ -50,7 +66,7 @@ class SeaGull(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "seagull". - :vartype kind: str + :vartype kind: Literal["seagull"] """ wingspan: Required[int] @@ -65,7 +81,7 @@ class Sparrow(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "sparrow". - :vartype kind: str + :vartype kind: Literal["sparrow"] """ wingspan: Required[int] @@ -74,20 +90,4 @@ class Sparrow(TypedDict, total=False): """Required. Default value is \"sparrow\".""" -class TRex(TypedDict, total=False): - """The second level legacy model in polymorphic single level inheritance. - - :ivar size: Required. - :vartype size: int - :ivar kind: Required. Default value is "t-rex". - :vartype kind: str - """ - - size: Required[int] - """Required.""" - kind: Required[Literal["t-rex"]] - """Required. Default value is \"t-rex\".""" - - Bird = Union[Eagle, Goose, SeaGull, Sparrow] -Dinosaur = Union[TRex] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/pyproject.toml index bb04ce600ef5..0f735fcda336 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_operations.py index 3584575e5e52..97b53cdb9a40 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import SingleDiscriminatorClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -139,6 +138,38 @@ def build_single_discriminator_get_legacy_model_request(**kwargs: Any) -> HttpRe return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) +def build_single_discriminator_get_no_subtypes_model_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/type/model/inheritance/single-discriminator/no-subtypes/model" + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_single_discriminator_put_no_subtypes_model_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/type/model/inheritance/single-discriminator/no-subtypes/model" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + class _SingleDiscriminatorClientOperationsMixin( ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SingleDiscriminatorClientConfiguration] ): @@ -212,11 +243,11 @@ def put_model(self, input: _models.Bird, *, content_type: str = "application/jso """ @overload - def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.singlediscriminator.types.Bird :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -240,12 +271,13 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", """ def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Bird, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any ) -> None: """put_model. - :param input: Is one of the following types: Bird, JSON, IO[bytes] Required. - :type input: ~typetest.model.singlediscriminator.models.Bird or JSON or IO[bytes] + :param input: Is either a Bird type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Bird or + ~typetest.model.singlediscriminator.types.Bird or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -365,11 +397,11 @@ def put_recursive_model( """ @overload - def put_recursive_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_recursive_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_recursive_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.singlediscriminator.types.Bird :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -393,12 +425,13 @@ def put_recursive_model(self, input: IO[bytes], *, content_type: str = "applicat """ def put_recursive_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.Bird, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any ) -> None: """put_recursive_model. - :param input: Is one of the following types: Bird, JSON, IO[bytes] Required. - :type input: ~typetest.model.singlediscriminator.models.Bird or JSON or IO[bytes] + :param input: Is either a Bird type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Bird or + ~typetest.model.singlediscriminator.types.Bird or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -608,3 +641,159 @@ def get_legacy_model(self, **kwargs: Any) -> _models.Dinosaur: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + def get_no_subtypes_model(self, **kwargs: Any) -> _models.Fish: + """get_no_subtypes_model. + + :return: Fish. The Fish is compatible with MutableMapping + :rtype: ~typetest.model.singlediscriminator.models.Fish + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Fish] = kwargs.pop("cls", None) + + _request = build_single_discriminator_get_no_subtypes_model_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Fish, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def put_no_subtypes_model( + self, input: _models.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.models.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def put_no_subtypes_model( + self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.types.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def put_no_subtypes_model(self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def put_no_subtypes_model( # pylint: disable=inconsistent-return-statements + self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Fish or + ~typetest.model.singlediscriminator.types.Fish or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(input, (IOBase, bytes)): + _content = input + else: + _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_single_discriminator_put_no_subtypes_model_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_operations.py index 880f14b3ab51..03d21c1f17a1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_operations.py @@ -19,21 +19,22 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_single_discriminator_get_legacy_model_request, build_single_discriminator_get_missing_discriminator_request, build_single_discriminator_get_model_request, + build_single_discriminator_get_no_subtypes_model_request, build_single_discriminator_get_recursive_model_request, build_single_discriminator_get_wrong_discriminator_request, build_single_discriminator_put_model_request, + build_single_discriminator_put_no_subtypes_model_request, build_single_discriminator_put_recursive_model_request, ) from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import SingleDiscriminatorClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -113,11 +114,11 @@ async def put_model(self, input: _models.Bird, *, content_type: str = "applicati """ @overload - async def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model(self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.singlediscriminator.types.Bird :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -140,11 +141,12 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_model(self, input: Union[_models.Bird, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_model(self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any) -> None: """put_model. - :param input: Is one of the following types: Bird, JSON, IO[bytes] Required. - :type input: ~typetest.model.singlediscriminator.models.Bird or JSON or IO[bytes] + :param input: Is either a Bird type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Bird or + ~typetest.model.singlediscriminator.types.Bird or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -268,11 +270,13 @@ async def put_recursive_model( """ @overload - async def put_recursive_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_recursive_model( + self, input: _types.Bird, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_recursive_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.singlediscriminator.types.Bird :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -297,11 +301,12 @@ async def put_recursive_model( :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_recursive_model(self, input: Union[_models.Bird, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_recursive_model(self, input: Union[_models.Bird, _types.Bird, IO[bytes]], **kwargs: Any) -> None: """put_recursive_model. - :param input: Is one of the following types: Bird, JSON, IO[bytes] Required. - :type input: ~typetest.model.singlediscriminator.models.Bird or JSON or IO[bytes] + :param input: Is either a Bird type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Bird or + ~typetest.model.singlediscriminator.types.Bird or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -519,3 +524,163 @@ async def get_legacy_model(self, **kwargs: Any) -> _models.Dinosaur: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + async def get_no_subtypes_model(self, **kwargs: Any) -> _models.Fish: + """get_no_subtypes_model. + + :return: Fish. The Fish is compatible with MutableMapping + :rtype: ~typetest.model.singlediscriminator.models.Fish + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Fish] = kwargs.pop("cls", None) + + _request = build_single_discriminator_get_no_subtypes_model_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run( # type: ignore + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Fish, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def put_no_subtypes_model( + self, input: _models.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.models.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def put_no_subtypes_model( + self, input: _types.Fish, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: ~typetest.model.singlediscriminator.types.Fish + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def put_no_subtypes_model( + self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """put_no_subtypes_model. + + :param input: Required. + :type input: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def put_no_subtypes_model(self, input: Union[_models.Fish, _types.Fish, IO[bytes]], **kwargs: Any) -> None: + """put_no_subtypes_model. + + :param input: Is either a Fish type or a IO[bytes] type. Required. + :type input: ~typetest.model.singlediscriminator.models.Fish or + ~typetest.model.singlediscriminator.types.Fish or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(input, (IOBase, bytes)): + _content = input + else: + _content = json.dumps(input, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_single_discriminator_put_no_subtypes_model_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run( # type: ignore + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/__init__.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/__init__.py index 04145d222153..fa5b9ccbc703 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/__init__.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/__init__.py @@ -11,6 +11,7 @@ Bird, Dinosaur, Eagle, + Fish, Goose, SeaGull, Sparrow, @@ -24,6 +25,7 @@ "Bird", "Dinosaur", "Eagle", + "Fish", "Goose", "SeaGull", "Sparrow", diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_models.py index 218105b583be..5b2301b58c83 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_models.py @@ -129,6 +129,39 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.kind = "eagle" # type: ignore +class Fish(_Model): + """A discriminated model with no defined subtypes. The discriminator is declared but no models + extend it. + + :ivar kind: Required. + :vartype kind: str + :ivar size: Required. + :vartype size: int + """ + + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + size: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + size: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class Goose(Bird, discriminator="goose"): """The second level model in polymorphic single level inheritance. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/types.py index e4c53efa0f72..59547a197b36 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-singlediscriminator/typetest/model/singlediscriminator/types.py @@ -11,13 +11,13 @@ class Eagle(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "eagle". - :vartype kind: str + :vartype kind: Literal["eagle"] :ivar friends: - :vartype friends: list[~typetest.model.singlediscriminator.models.Bird] + :vartype friends: list["Bird"] :ivar hate: - :vartype hate: dict[str, ~typetest.model.singlediscriminator.models.Bird] + :vartype hate: dict[str, "Bird"] :ivar partner: - :vartype partner: ~typetest.model.singlediscriminator.models.Bird + :vartype partner: "Bird" """ wingspan: Required[int] @@ -29,13 +29,29 @@ class Eagle(TypedDict, total=False): partner: "Bird" +class Fish(TypedDict, total=False): + """A discriminated model with no defined subtypes. The discriminator is declared but no models + extend it. + + :ivar kind: Required. + :vartype kind: str + :ivar size: Required. + :vartype size: int + """ + + kind: Required[str] + """Required.""" + size: Required[int] + """Required.""" + + class Goose(TypedDict, total=False): """The second level model in polymorphic single level inheritance. :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "goose". - :vartype kind: str + :vartype kind: Literal["goose"] """ wingspan: Required[int] @@ -50,7 +66,7 @@ class SeaGull(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "seagull". - :vartype kind: str + :vartype kind: Literal["seagull"] """ wingspan: Required[int] @@ -65,7 +81,7 @@ class Sparrow(TypedDict, total=False): :ivar wingspan: Required. :vartype wingspan: int :ivar kind: Required. Default value is "sparrow". - :vartype kind: str + :vartype kind: Literal["sparrow"] """ wingspan: Required[int] @@ -74,20 +90,4 @@ class Sparrow(TypedDict, total=False): """Required. Default value is \"sparrow\".""" -class TRex(TypedDict, total=False): - """The second level legacy model in polymorphic single level inheritance. - - :ivar size: Required. - :vartype size: int - :ivar kind: Required. Default value is "t-rex". - :vartype kind: str - """ - - size: Required[int] - """Required.""" - kind: Required[Literal["t-rex"]] - """Required. Default value is \"t-rex\".""" - - Bird = Union[Eagle, Goose, SeaGull, Sparrow] -Dinosaur = Union[TRex] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/README.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/README.md new file mode 100644 index 000000000000..e168787b1af1 --- /dev/null +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/README.md @@ -0,0 +1,3 @@ +# ⚠️ TEST CODE — DO NOT INSTALL FROM PYPI + +This is not a published Azure SDK package; it exists only for testing purposes. Do not install from PyPI. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/pyproject.toml index 217365d1639d..ceade081167a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_operations/_operations.py index a067445b27db..130c09a16b76 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_operations/_operations.py @@ -1,7 +1,6 @@ # coding=utf-8 from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +from typing import Any, Callable, Optional, TypeVar from corehttp.exceptions import ( ClientAuthenticationError, @@ -18,7 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import types +from .. import types as _types from .._configuration import UsageClientConfiguration from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC @@ -30,18 +29,17 @@ _SERIALIZER.client_side_validation = False -def build_usage_input_request(**kwargs: Any) -> HttpRequest: +def build_usage_input_request(*, json: _types.InputRecord, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type: str = kwargs.pop("content_type") # Construct URL _url = "/type/model/usage/input" # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) def build_usage_output_request(**kwargs: Any) -> HttpRequest: @@ -58,68 +56,29 @@ def build_usage_output_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_usage_input_and_output_request(**kwargs: Any) -> HttpRequest: +def build_usage_input_and_output_request(*, json: _types.InputOutputRecord, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type: str = kwargs.pop("content_type") accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/type/model/usage/input-output" # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) class _UsageClientOperationsMixin(ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], UsageClientConfiguration]): - @overload - def input(self, input: types.InputRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: + def input(self, input: _types.InputRecord, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """input. :param input: Required. :type input: ~typetest.model.usage.typeddictonly.types.InputRecord - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~corehttp.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - input = { - "requiredProp": "str" - } - """ - - @overload - def input(self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: - """input. - - :param input: Required. - :type input: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~corehttp.exceptions.HttpResponseError: - """ - - def input( # pylint: disable=inconsistent-return-statements - self, input: Union[types.InputRecord, IO[bytes]], **kwargs: Any - ) -> None: - """input. - - :param input: Is either a InputRecord type or a IO[bytes] type. Required. - :type input: ~typetest.model.usage.typeddictonly.types.InputRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -143,21 +102,14 @@ def input( # pylint: disable=inconsistent-return-statements _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) cls: ClsType[None] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(input, (IOBase, bytes)): - _content = input - else: - _json = input + _json = input _request = build_usage_input_request( content_type=content_type, json=_json, - content=_content, headers=_headers, params=_params, ) @@ -178,7 +130,7 @@ def input( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) # type: ignore - def output(self, **kwargs: Any) -> types.OutputRecord: + def output(self, **kwargs: Any) -> _types.OutputRecord: """output. :return: OutputRecord @@ -204,7 +156,7 @@ def output(self, **kwargs: Any) -> types.OutputRecord: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[types.OutputRecord] = kwargs.pop("cls", None) + cls: ClsType[_types.OutputRecord] = kwargs.pop("cls", None) _request = build_usage_output_request( headers=_headers, @@ -243,66 +195,11 @@ def output(self, **kwargs: Any) -> types.OutputRecord: return deserialized # type: ignore - @overload - def input_and_output( - self, body: types.InputOutputRecord, *, content_type: str = "application/json", **kwargs: Any - ) -> types.InputOutputRecord: + def input_and_output(self, body: _types.InputOutputRecord, **kwargs: Any) -> _types.InputOutputRecord: """input_and_output. :param body: Required. :type body: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: InputOutputRecord - :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :raises ~corehttp.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "requiredProp": "str" - } - - # response body for status code(s): 200 - response == { - "requiredProp": "str" - } - """ - - @overload - def input_and_output( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> types.InputOutputRecord: - """input_and_output. - - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: InputOutputRecord - :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :raises ~corehttp.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "requiredProp": "str" - } - """ - - def input_and_output( - self, body: Union[types.InputOutputRecord, IO[bytes]], **kwargs: Any - ) -> types.InputOutputRecord: - """input_and_output. - - :param body: Is either a InputOutputRecord type or a IO[bytes] type. Required. - :type body: ~typetest.model.usage.typeddictonly.types.InputOutputRecord or IO[bytes] :return: InputOutputRecord :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord :raises ~corehttp.exceptions.HttpResponseError: @@ -331,21 +228,14 @@ def input_and_output( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[types.InputOutputRecord] = kwargs.pop("cls", None) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[_types.InputOutputRecord] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = body + _json = body _request = build_usage_input_and_output_request( content_type=content_type, json=_json, - content=_content, headers=_headers, params=_params, ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/aio/_operations/_operations.py index 8f26679b2ff1..73ab43710607 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage-typeddictonly/typetest/model/usage/typeddictonly/aio/_operations/_operations.py @@ -1,7 +1,6 @@ # coding=utf-8 from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Optional, TypeVar, Union, overload +from typing import Any, Callable, Optional, TypeVar from corehttp.exceptions import ( ClientAuthenticationError, @@ -18,7 +17,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import types +from ... import types as _types from ..._operations._operations import ( build_usage_input_and_output_request, build_usage_input_request, @@ -35,47 +34,11 @@ class _UsageClientOperationsMixin( ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], UsageClientConfiguration] ): - @overload - async def input(self, input: types.InputRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def input(self, input: _types.InputRecord, **kwargs: Any) -> None: """input. :param input: Required. :type input: ~typetest.model.usage.typeddictonly.types.InputRecord - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~corehttp.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - input = { - "requiredProp": "str" - } - """ - - @overload - async def input(self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: - """input. - - :param input: Required. - :type input: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~corehttp.exceptions.HttpResponseError: - """ - - async def input(self, input: Union[types.InputRecord, IO[bytes]], **kwargs: Any) -> None: - """input. - - :param input: Is either a InputRecord type or a IO[bytes] type. Required. - :type input: ~typetest.model.usage.typeddictonly.types.InputRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -99,21 +62,14 @@ async def input(self, input: Union[types.InputRecord, IO[bytes]], **kwargs: Any) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) cls: ClsType[None] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(input, (IOBase, bytes)): - _content = input - else: - _json = input + _json = input _request = build_usage_input_request( content_type=content_type, json=_json, - content=_content, headers=_headers, params=_params, ) @@ -136,7 +92,7 @@ async def input(self, input: Union[types.InputRecord, IO[bytes]], **kwargs: Any) if cls: return cls(pipeline_response, None, {}) # type: ignore - async def output(self, **kwargs: Any) -> types.OutputRecord: + async def output(self, **kwargs: Any) -> _types.OutputRecord: """output. :return: OutputRecord @@ -162,7 +118,7 @@ async def output(self, **kwargs: Any) -> types.OutputRecord: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[types.OutputRecord] = kwargs.pop("cls", None) + cls: ClsType[_types.OutputRecord] = kwargs.pop("cls", None) _request = build_usage_output_request( headers=_headers, @@ -203,66 +159,11 @@ async def output(self, **kwargs: Any) -> types.OutputRecord: return deserialized # type: ignore - @overload - async def input_and_output( - self, body: types.InputOutputRecord, *, content_type: str = "application/json", **kwargs: Any - ) -> types.InputOutputRecord: + async def input_and_output(self, body: _types.InputOutputRecord, **kwargs: Any) -> _types.InputOutputRecord: """input_and_output. :param body: Required. :type body: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: InputOutputRecord - :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :raises ~corehttp.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "requiredProp": "str" - } - - # response body for status code(s): 200 - response == { - "requiredProp": "str" - } - """ - - @overload - async def input_and_output( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> types.InputOutputRecord: - """input_and_output. - - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: InputOutputRecord - :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord - :raises ~corehttp.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "requiredProp": "str" - } - """ - - async def input_and_output( - self, body: Union[types.InputOutputRecord, IO[bytes]], **kwargs: Any - ) -> types.InputOutputRecord: - """input_and_output. - - :param body: Is either a InputOutputRecord type or a IO[bytes] type. Required. - :type body: ~typetest.model.usage.typeddictonly.types.InputOutputRecord or IO[bytes] :return: InputOutputRecord :rtype: ~typetest.model.usage.typeddictonly.types.InputOutputRecord :raises ~corehttp.exceptions.HttpResponseError: @@ -291,21 +192,14 @@ async def input_and_output( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[types.InputOutputRecord] = kwargs.pop("cls", None) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[_types.InputOutputRecord] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _json = body + _json = body _request = build_usage_input_and_output_request( content_type=content_type, json=_json, - content=_content, headers=_headers, params=_params, ) diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/pyproject.toml index 3f493fac8dcb..cbe5e5becccb 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_operations/_operations.py index 2f7c9ccd852f..7a8ea4169074 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import UsageClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -95,11 +94,11 @@ def input(self, input: _models.InputRecord, *, content_type: str = "application/ """ @overload - def input(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def input(self, input: _types.InputRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """input. :param input: Required. - :type input: JSON + :type input: ~typetest.model.usage.types.InputRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -123,12 +122,13 @@ def input(self, input: IO[bytes], *, content_type: str = "application/json", **k """ def input( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.InputRecord, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.InputRecord, _types.InputRecord, IO[bytes]], **kwargs: Any ) -> None: """input. - :param input: Is one of the following types: InputRecord, JSON, IO[bytes] Required. - :type input: ~typetest.model.usage.models.InputRecord or JSON or IO[bytes] + :param input: Is either a InputRecord type or a IO[bytes] type. Required. + :type input: ~typetest.model.usage.models.InputRecord or + ~typetest.model.usage.types.InputRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -249,12 +249,12 @@ def input_and_output( @overload def input_and_output( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.InputOutputRecord, *, content_type: str = "application/json", **kwargs: Any ) -> _models.InputOutputRecord: """input_and_output. :param body: Required. - :type body: JSON + :type body: ~typetest.model.usage.types.InputOutputRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -280,12 +280,13 @@ def input_and_output( """ def input_and_output( - self, body: Union[_models.InputOutputRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.InputOutputRecord, _types.InputOutputRecord, IO[bytes]], **kwargs: Any ) -> _models.InputOutputRecord: """input_and_output. - :param body: Is one of the following types: InputOutputRecord, JSON, IO[bytes] Required. - :type body: ~typetest.model.usage.models.InputOutputRecord or JSON or IO[bytes] + :param body: Is either a InputOutputRecord type or a IO[bytes] type. Required. + :type body: ~typetest.model.usage.models.InputOutputRecord or + ~typetest.model.usage.types.InputOutputRecord or IO[bytes] :return: InputOutputRecord. The InputOutputRecord is compatible with MutableMapping :rtype: ~typetest.model.usage.models.InputOutputRecord :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_operations/_operations.py index 822e4c6fab78..e647871bd19d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_usage_input_and_output_request, build_usage_input_request, @@ -29,7 +29,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import UsageClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -53,11 +52,11 @@ async def input(self, input: _models.InputRecord, *, content_type: str = "applic """ @overload - async def input(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def input(self, input: _types.InputRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """input. :param input: Required. - :type input: JSON + :type input: ~typetest.model.usage.types.InputRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -80,11 +79,12 @@ async def input(self, input: IO[bytes], *, content_type: str = "application/json :raises ~corehttp.exceptions.HttpResponseError: """ - async def input(self, input: Union[_models.InputRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def input(self, input: Union[_models.InputRecord, _types.InputRecord, IO[bytes]], **kwargs: Any) -> None: """input. - :param input: Is one of the following types: InputRecord, JSON, IO[bytes] Required. - :type input: ~typetest.model.usage.models.InputRecord or JSON or IO[bytes] + :param input: Is either a InputRecord type or a IO[bytes] type. Required. + :type input: ~typetest.model.usage.models.InputRecord or + ~typetest.model.usage.types.InputRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -209,12 +209,12 @@ async def input_and_output( @overload async def input_and_output( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.InputOutputRecord, *, content_type: str = "application/json", **kwargs: Any ) -> _models.InputOutputRecord: """input_and_output. :param body: Required. - :type body: JSON + :type body: ~typetest.model.usage.types.InputOutputRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -240,12 +240,13 @@ async def input_and_output( """ async def input_and_output( - self, body: Union[_models.InputOutputRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.InputOutputRecord, _types.InputOutputRecord, IO[bytes]], **kwargs: Any ) -> _models.InputOutputRecord: """input_and_output. - :param body: Is one of the following types: InputOutputRecord, JSON, IO[bytes] Required. - :type body: ~typetest.model.usage.models.InputOutputRecord or JSON or IO[bytes] + :param body: Is either a InputOutputRecord type or a IO[bytes] type. Required. + :type body: ~typetest.model.usage.models.InputOutputRecord or + ~typetest.model.usage.types.InputOutputRecord or IO[bytes] :return: InputOutputRecord. The InputOutputRecord is compatible with MutableMapping :rtype: ~typetest.model.usage.models.InputOutputRecord :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/types.py index 492e8eb34ea9..5c912a387696 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-usage/typetest/model/usage/types.py @@ -23,14 +23,3 @@ class InputRecord(TypedDict, total=False): requiredProp: Required[str] """Required.""" - - -class OutputRecord(TypedDict, total=False): - """Record used in operation return type. - - :ivar required_prop: Required. - :vartype required_prop: str - """ - - requiredProp: Required[str] - """Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/pyproject.toml index 146830b5290b..321422422d00 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_operations/_operations.py index 0eb7eea7f21f..7ff1c3b9e9ea 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import VisibilityClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -169,12 +168,12 @@ def get_model( @overload def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -204,12 +203,17 @@ def get_model( """ def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -294,12 +298,12 @@ def head_model( @overload def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> bool: """head_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -329,12 +333,17 @@ def head_model( """ def head_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> bool: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: bool @@ -404,11 +413,13 @@ def put_model( """ @overload - def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -432,12 +443,13 @@ def put_model(self, input: IO[bytes], *, content_type: str = "application/json", """ def put_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -503,11 +515,13 @@ def patch_model( """ @overload - def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -531,12 +545,13 @@ def patch_model(self, input: IO[bytes], *, content_type: str = "application/json """ def patch_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -602,11 +617,13 @@ def post_model( """ @overload - def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -630,12 +647,13 @@ def post_model(self, input: IO[bytes], *, content_type: str = "application/json" """ def post_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -701,11 +719,13 @@ def delete_model( """ @overload - def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -729,12 +749,13 @@ def delete_model(self, input: IO[bytes], *, content_type: str = "application/jso """ def delete_model( # pylint: disable=inconsistent-return-statements - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -801,12 +822,12 @@ def put_read_only_model( @overload def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -832,12 +853,13 @@ def put_read_only_model( """ def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.ReadOnlyModel or + ~typetest.model.visibility.types.ReadOnlyModel or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~typetest.model.visibility.models.ReadOnlyModel :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_operations/_operations.py index 7dcbda98e8a2..b2e61f97b508 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import ( build_visibility_delete_model_request, build_visibility_get_model_request, @@ -33,7 +33,6 @@ from ..._utils.utils import ClientMixinABC from .._configuration import VisibilityClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -62,12 +61,12 @@ async def get_model( @overload async def get_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> _models.VisibilityModel: """get_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -97,12 +96,17 @@ async def get_model( """ async def get_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> _models.VisibilityModel: """get_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: VisibilityModel. The VisibilityModel is compatible with MutableMapping @@ -189,12 +193,12 @@ async def head_model( @overload async def head_model( - self, input: JSON, *, query_prop: int, content_type: str = "application/json", **kwargs: Any + self, input: _types.VisibilityModel, *, query_prop: int, content_type: str = "application/json", **kwargs: Any ) -> bool: """head_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -224,12 +228,17 @@ async def head_model( """ async def head_model( - self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], *, query_prop: int, **kwargs: Any + self, + input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], + *, + query_prop: int, + **kwargs: Any ) -> bool: """head_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :keyword query_prop: Required int32, illustrating a query property. Required. :paramtype query_prop: int :return: bool @@ -301,11 +310,13 @@ async def put_model( """ @overload - async def put_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """put_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -328,11 +339,14 @@ async def put_model(self, input: IO[bytes], *, content_type: str = "application/ :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """put_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -400,11 +414,13 @@ async def patch_model( """ @overload - async def patch_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def patch_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """patch_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -427,11 +443,14 @@ async def patch_model(self, input: IO[bytes], *, content_type: str = "applicatio :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """patch_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -499,11 +518,13 @@ async def post_model( """ @overload - async def post_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def post_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """post_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -526,11 +547,14 @@ async def post_model(self, input: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def post_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def post_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """post_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -598,11 +622,13 @@ async def delete_model( """ @overload - async def delete_model(self, input: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def delete_model( + self, input: _types.VisibilityModel, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """delete_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.VisibilityModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -625,11 +651,14 @@ async def delete_model(self, input: IO[bytes], *, content_type: str = "applicati :raises ~corehttp.exceptions.HttpResponseError: """ - async def delete_model(self, input: Union[_models.VisibilityModel, JSON, IO[bytes]], **kwargs: Any) -> None: + async def delete_model( + self, input: Union[_models.VisibilityModel, _types.VisibilityModel, IO[bytes]], **kwargs: Any + ) -> None: """delete_model. - :param input: Is one of the following types: VisibilityModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.VisibilityModel or JSON or IO[bytes] + :param input: Is either a VisibilityModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.VisibilityModel or + ~typetest.model.visibility.types.VisibilityModel or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -698,12 +727,12 @@ async def put_read_only_model( @overload async def put_read_only_model( - self, input: JSON, *, content_type: str = "application/json", **kwargs: Any + self, input: _types.ReadOnlyModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. :param input: Required. - :type input: JSON + :type input: ~typetest.model.visibility.types.ReadOnlyModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -729,12 +758,13 @@ async def put_read_only_model( """ async def put_read_only_model( - self, input: Union[_models.ReadOnlyModel, JSON, IO[bytes]], **kwargs: Any + self, input: Union[_models.ReadOnlyModel, _types.ReadOnlyModel, IO[bytes]], **kwargs: Any ) -> _models.ReadOnlyModel: """put_read_only_model. - :param input: Is one of the following types: ReadOnlyModel, JSON, IO[bytes] Required. - :type input: ~typetest.model.visibility.models.ReadOnlyModel or JSON or IO[bytes] + :param input: Is either a ReadOnlyModel type or a IO[bytes] type. Required. + :type input: ~typetest.model.visibility.models.ReadOnlyModel or + ~typetest.model.visibility.types.ReadOnlyModel or IO[bytes] :return: ReadOnlyModel. The ReadOnlyModel is compatible with MutableMapping :rtype: ~typetest.model.visibility.models.ReadOnlyModel :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-model-visibility/typetest/model/visibility/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/pyproject.toml index c7fa8b58b5cd..dbe38a212e2d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_operations.py index 64a521444221..5f47ea903989 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_operations.py @@ -20,7 +20,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -89,7 +89,6 @@ ) from .._configuration import AdditionalPropertiesClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -185,11 +184,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.ExtendsUnknownAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -213,14 +214,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ async def put( - self, body: Union[_models.ExtendsUnknownAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ExtendsUnknownAdditionalProperties, _types.ExtendsUnknownAdditionalProperties, IO[bytes]], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsUnknownAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalProperties - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalProperties or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -367,11 +371,18 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.ExtendsUnknownAdditionalPropertiesDerived, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -395,15 +406,22 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ async def put( - self, body: Union[_models.ExtendsUnknownAdditionalPropertiesDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsUnknownAdditionalPropertiesDerived, + _types.ExtendsUnknownAdditionalPropertiesDerived, + IO[bytes], + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsUnknownAdditionalPropertiesDerived, - JSON, IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalPropertiesDerived type or a IO[bytes] + type. Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalPropertiesDerived or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDerived or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -550,11 +568,18 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.ExtendsUnknownAdditionalPropertiesDiscriminated, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDiscriminated :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -578,15 +603,23 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ async def put( - self, body: Union[_models.ExtendsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsUnknownAdditionalPropertiesDiscriminated, + _types.ExtendsUnknownAdditionalPropertiesDiscriminated, + IO[bytes], + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: - ExtendsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalPropertiesDiscriminated type or a + IO[bytes] type. Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalPropertiesDiscriminated - or JSON or IO[bytes] + or + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDiscriminated + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -727,11 +760,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IsUnknownAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsUnknownAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -754,13 +789,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.IsUnknownAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.IsUnknownAdditionalProperties, _types.IsUnknownAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsUnknownAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -905,11 +944,17 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.IsUnknownAdditionalPropertiesDerived, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -933,14 +978,19 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ async def put( - self, body: Union[_models.IsUnknownAdditionalPropertiesDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.IsUnknownAdditionalPropertiesDerived, _types.IsUnknownAdditionalPropertiesDerived, IO[bytes] + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalPropertiesDerived, JSON, - IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalPropertiesDerived type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalPropertiesDerived - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDerived or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1087,11 +1137,18 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.IsUnknownAdditionalPropertiesDiscriminated, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDiscriminated :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1115,15 +1172,22 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ async def put( - self, body: Union[_models.IsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.IsUnknownAdditionalPropertiesDiscriminated, + _types.IsUnknownAdditionalPropertiesDiscriminated, + IO[bytes], + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalPropertiesDiscriminated, - JSON, IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalPropertiesDiscriminated type or a IO[bytes] + type. Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalPropertiesDiscriminated or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDiscriminated or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1264,11 +1328,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.ExtendsStringAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsStringAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1291,13 +1357,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.ExtendsStringAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.ExtendsStringAdditionalProperties, _types.ExtendsStringAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsStringAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsStringAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsStringAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsStringAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1438,11 +1508,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IsStringAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsStringAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1465,13 +1537,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.IsStringAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.IsStringAdditionalProperties, _types.IsStringAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IsStringAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsStringAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsStringAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsStringAdditionalProperties or + ~typetest.property.additionalproperties.types.IsStringAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1611,11 +1686,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.SpreadStringRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadStringRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1638,12 +1715,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.SpreadStringRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.SpreadStringRecord, _types.SpreadStringRecord, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadStringRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadStringRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadStringRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadStringRecord or + ~typetest.property.additionalproperties.types.SpreadStringRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1784,11 +1863,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.ExtendsFloatAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsFloatAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1811,13 +1892,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.ExtendsFloatAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.ExtendsFloatAdditionalProperties, _types.ExtendsFloatAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsFloatAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsFloatAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsFloatAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsFloatAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1958,11 +2043,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IsFloatAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsFloatAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1985,13 +2072,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.IsFloatAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.IsFloatAdditionalProperties, _types.IsFloatAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IsFloatAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsFloatAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsFloatAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsFloatAdditionalProperties or + ~typetest.property.additionalproperties.types.IsFloatAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2131,11 +2221,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.SpreadFloatRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadFloatRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2158,12 +2250,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.SpreadFloatRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.SpreadFloatRecord, _types.SpreadFloatRecord, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadFloatRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadFloatRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadFloatRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadFloatRecord or + ~typetest.property.additionalproperties.types.SpreadFloatRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2304,11 +2398,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.ExtendsModelAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsModelAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2331,13 +2427,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.ExtendsModelAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.ExtendsModelAdditionalProperties, _types.ExtendsModelAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsModelAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsModelAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsModelAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsModelAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2478,11 +2578,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IsModelAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsModelAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2505,13 +2607,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.IsModelAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.IsModelAdditionalProperties, _types.IsModelAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IsModelAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsModelAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsModelAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsModelAdditionalProperties or + ~typetest.property.additionalproperties.types.IsModelAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2651,11 +2756,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.SpreadModelRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadModelRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2678,12 +2785,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.SpreadModelRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.SpreadModelRecord, _types.SpreadModelRecord, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadModelRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadModelRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadModelRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadModelRecord or + ~typetest.property.additionalproperties.types.SpreadModelRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2829,11 +2938,17 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.ExtendsModelArrayAdditionalProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsModelArrayAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2857,14 +2972,19 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ async def put( - self, body: Union[_models.ExtendsModelArrayAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsModelArrayAdditionalProperties, _types.ExtendsModelArrayAdditionalProperties, IO[bytes] + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsModelArrayAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsModelArrayAdditionalProperties type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.ExtendsModelArrayAdditionalProperties or JSON or + ~typetest.property.additionalproperties.models.ExtendsModelArrayAdditionalProperties or + ~typetest.property.additionalproperties.types.ExtendsModelArrayAdditionalProperties or IO[bytes] :return: None :rtype: None @@ -3006,11 +3126,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IsModelArrayAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsModelArrayAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3033,13 +3155,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.IsModelArrayAdditionalProperties, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.IsModelArrayAdditionalProperties, _types.IsModelArrayAdditionalProperties, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IsModelArrayAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a IsModelArrayAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsModelArrayAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsModelArrayAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3179,11 +3305,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.SpreadModelArrayRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadModelArrayRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3206,13 +3334,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.SpreadModelArrayRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.SpreadModelArrayRecord, _types.SpreadModelArrayRecord, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadModelArrayRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.SpreadModelArrayRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadModelArrayRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadModelArrayRecord or + ~typetest.property.additionalproperties.types.SpreadModelArrayRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3353,11 +3482,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadStringRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadStringRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3380,13 +3511,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DifferentSpreadStringRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadStringRecord, _types.DifferentSpreadStringRecord, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadStringRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadStringRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadStringRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3527,11 +3661,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadFloatRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadFloatRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3554,13 +3690,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DifferentSpreadFloatRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadFloatRecord, _types.DifferentSpreadFloatRecord, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadFloatRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadFloatRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadFloatRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3701,11 +3840,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadModelRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3728,13 +3869,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DifferentSpreadModelRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadModelRecord, _types.DifferentSpreadModelRecord, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadModelRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadModelRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3875,11 +4019,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadModelArrayRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3902,13 +4048,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DifferentSpreadModelArrayRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadModelArrayRecord, _types.DifferentSpreadModelArrayRecord, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelArrayRecord, JSON, - IO[bytes] Required. + :param body: body. Is either a DifferentSpreadModelArrayRecord type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelArrayRecord or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4049,11 +4199,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadStringDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadStringDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4076,13 +4228,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DifferentSpreadStringDerived, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadStringDerived, _types.DifferentSpreadStringDerived, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadStringDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadStringDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadStringDerived or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4223,11 +4378,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadFloatDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadFloatDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4250,13 +4407,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DifferentSpreadFloatDerived, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadFloatDerived, _types.DifferentSpreadFloatDerived, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadFloatDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadFloatDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadFloatDerived or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4397,11 +4557,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadModelDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4424,13 +4586,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DifferentSpreadModelDerived, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadModelDerived, _types.DifferentSpreadModelDerived, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadModelDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadModelDerived or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4571,11 +4736,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DifferentSpreadModelArrayDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4598,13 +4765,17 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DifferentSpreadModelArrayDerived, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.DifferentSpreadModelArrayDerived, _types.DifferentSpreadModelArrayDerived, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelArrayDerived, JSON, - IO[bytes] Required. + :param body: body. Is either a DifferentSpreadModelArrayDerived type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelArrayDerived or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayDerived or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4744,11 +4915,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.MultipleSpreadRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.MultipleSpreadRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4771,13 +4944,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.MultipleSpreadRecord, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.MultipleSpreadRecord, _types.MultipleSpreadRecord, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: MultipleSpreadRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.MultipleSpreadRecord or JSON or - IO[bytes] + :param body: body. Is either a MultipleSpreadRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.MultipleSpreadRecord or + ~typetest.property.additionalproperties.types.MultipleSpreadRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4917,11 +5091,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.SpreadRecordForUnion, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForUnion :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4944,13 +5120,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.SpreadRecordForUnion, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.SpreadRecordForUnion, _types.SpreadRecordForUnion, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForUnion, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.SpreadRecordForUnion or JSON or - IO[bytes] + :param body: body. Is either a SpreadRecordForUnion type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadRecordForUnion or + ~typetest.property.additionalproperties.types.SpreadRecordForUnion or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5095,11 +5272,17 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5123,14 +5306,19 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ async def put( - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion, _types.SpreadRecordForNonDiscriminatedUnion, IO[bytes] + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5276,11 +5464,17 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion2, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5304,14 +5498,19 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ async def put( - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion2, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion2, _types.SpreadRecordForNonDiscriminatedUnion2, IO[bytes] + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion2, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion2 type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion2 or JSON or + ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion2 or + ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion2 or IO[bytes] :return: None :rtype: None @@ -5458,11 +5657,17 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion3, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5486,14 +5691,19 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", """ async def put( - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion3, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion3, _types.SpreadRecordForNonDiscriminatedUnion3, IO[bytes] + ], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion3, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion3 type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion3 or JSON or + ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion3 or + ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion3 or IO[bytes] :return: None :rtype: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_operations.py index 0edcfc3c5907..c193a2e8a83f 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_operations.py @@ -20,12 +20,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import AdditionalPropertiesClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -1008,11 +1007,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.ExtendsUnknownAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1036,14 +1037,17 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsUnknownAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ExtendsUnknownAdditionalProperties, _types.ExtendsUnknownAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsUnknownAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalProperties - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalProperties or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1190,11 +1194,18 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.ExtendsUnknownAdditionalPropertiesDerived, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1218,15 +1229,22 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsUnknownAdditionalPropertiesDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsUnknownAdditionalPropertiesDerived, + _types.ExtendsUnknownAdditionalPropertiesDerived, + IO[bytes], + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsUnknownAdditionalPropertiesDerived, - JSON, IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalPropertiesDerived type or a IO[bytes] + type. Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalPropertiesDerived or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDerived or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1373,11 +1391,18 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.ExtendsUnknownAdditionalPropertiesDiscriminated, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDiscriminated :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1401,15 +1426,23 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsUnknownAdditionalPropertiesDiscriminated, + _types.ExtendsUnknownAdditionalPropertiesDiscriminated, + IO[bytes], + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: - ExtendsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes] Required. + :param body: body. Is either a ExtendsUnknownAdditionalPropertiesDiscriminated type or a + IO[bytes] type. Required. :type body: ~typetest.property.additionalproperties.models.ExtendsUnknownAdditionalPropertiesDiscriminated - or JSON or IO[bytes] + or + ~typetest.property.additionalproperties.types.ExtendsUnknownAdditionalPropertiesDiscriminated + or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1550,11 +1583,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.IsUnknownAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsUnknownAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1578,14 +1613,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsUnknownAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.IsUnknownAdditionalProperties, _types.IsUnknownAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsUnknownAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1730,11 +1767,17 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.IsUnknownAdditionalPropertiesDerived, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1758,14 +1801,19 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsUnknownAdditionalPropertiesDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.IsUnknownAdditionalPropertiesDerived, _types.IsUnknownAdditionalPropertiesDerived, IO[bytes] + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalPropertiesDerived, JSON, - IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalPropertiesDerived type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalPropertiesDerived - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDerived or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1912,11 +1960,18 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.IsUnknownAdditionalPropertiesDiscriminated, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: + ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDiscriminated :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1940,15 +1995,22 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsUnknownAdditionalPropertiesDiscriminated, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.IsUnknownAdditionalPropertiesDiscriminated, + _types.IsUnknownAdditionalPropertiesDiscriminated, + IO[bytes], + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsUnknownAdditionalPropertiesDiscriminated, - JSON, IO[bytes] Required. + :param body: body. Is either a IsUnknownAdditionalPropertiesDiscriminated type or a IO[bytes] + type. Required. :type body: ~typetest.property.additionalproperties.models.IsUnknownAdditionalPropertiesDiscriminated or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsUnknownAdditionalPropertiesDiscriminated or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2089,11 +2151,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.ExtendsStringAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsStringAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2117,14 +2181,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsStringAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ExtendsStringAdditionalProperties, _types.ExtendsStringAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsStringAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsStringAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsStringAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsStringAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2265,11 +2331,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.IsStringAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsStringAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2293,14 +2361,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsStringAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.IsStringAdditionalProperties, _types.IsStringAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsStringAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsStringAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsStringAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsStringAdditionalProperties or + ~typetest.property.additionalproperties.types.IsStringAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2438,11 +2507,11 @@ def put(self, body: _models.SpreadStringRecord, *, content_type: str = "applicat """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.SpreadStringRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadStringRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2466,13 +2535,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadStringRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SpreadStringRecord, _types.SpreadStringRecord, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadStringRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadStringRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadStringRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadStringRecord or + ~typetest.property.additionalproperties.types.SpreadStringRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2613,11 +2682,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.ExtendsFloatAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsFloatAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2641,14 +2712,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsFloatAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ExtendsFloatAdditionalProperties, _types.ExtendsFloatAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsFloatAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsFloatAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsFloatAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsFloatAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2789,11 +2862,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.IsFloatAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsFloatAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2817,14 +2892,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsFloatAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.IsFloatAdditionalProperties, _types.IsFloatAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsFloatAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsFloatAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsFloatAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsFloatAdditionalProperties or + ~typetest.property.additionalproperties.types.IsFloatAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2962,11 +3038,11 @@ def put(self, body: _models.SpreadFloatRecord, *, content_type: str = "applicati """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.SpreadFloatRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadFloatRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2990,13 +3066,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadFloatRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SpreadFloatRecord, _types.SpreadFloatRecord, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadFloatRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadFloatRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadFloatRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadFloatRecord or + ~typetest.property.additionalproperties.types.SpreadFloatRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3137,11 +3213,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.ExtendsModelAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsModelAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3165,14 +3243,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsModelAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.ExtendsModelAdditionalProperties, _types.ExtendsModelAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsModelAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsModelAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.ExtendsModelAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.ExtendsModelAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3313,11 +3393,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.IsModelAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsModelAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3341,14 +3423,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsModelAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.IsModelAdditionalProperties, _types.IsModelAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsModelAdditionalProperties, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.IsModelAdditionalProperties or JSON - or IO[bytes] + :param body: body. Is either a IsModelAdditionalProperties type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.IsModelAdditionalProperties or + ~typetest.property.additionalproperties.types.IsModelAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3486,11 +3569,11 @@ def put(self, body: _models.SpreadModelRecord, *, content_type: str = "applicati """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.SpreadModelRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadModelRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3514,13 +3597,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadModelRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SpreadModelRecord, _types.SpreadModelRecord, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadModelRecord, JSON, IO[bytes] Required. - :type body: ~typetest.property.additionalproperties.models.SpreadModelRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadModelRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadModelRecord or + ~typetest.property.additionalproperties.types.SpreadModelRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3666,11 +3749,17 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.ExtendsModelArrayAdditionalProperties, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.ExtendsModelArrayAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3694,14 +3783,19 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtendsModelArrayAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.ExtendsModelArrayAdditionalProperties, _types.ExtendsModelArrayAdditionalProperties, IO[bytes] + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtendsModelArrayAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a ExtendsModelArrayAdditionalProperties type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.ExtendsModelArrayAdditionalProperties or JSON or + ~typetest.property.additionalproperties.models.ExtendsModelArrayAdditionalProperties or + ~typetest.property.additionalproperties.types.ExtendsModelArrayAdditionalProperties or IO[bytes] :return: None :rtype: None @@ -3843,11 +3937,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.IsModelArrayAdditionalProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.IsModelArrayAdditionalProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3871,14 +3967,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IsModelArrayAdditionalProperties, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.IsModelArrayAdditionalProperties, _types.IsModelArrayAdditionalProperties, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: IsModelArrayAdditionalProperties, JSON, - IO[bytes] Required. + :param body: body. Is either a IsModelArrayAdditionalProperties type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.IsModelArrayAdditionalProperties or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.IsModelArrayAdditionalProperties or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4018,11 +4116,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.SpreadModelArrayRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadModelArrayRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4046,14 +4146,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadModelArrayRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SpreadModelArrayRecord, _types.SpreadModelArrayRecord, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadModelArrayRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.SpreadModelArrayRecord or JSON or - IO[bytes] + :param body: body. Is either a SpreadModelArrayRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadModelArrayRecord or + ~typetest.property.additionalproperties.types.SpreadModelArrayRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4194,11 +4293,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadStringRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadStringRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4222,14 +4323,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadStringRecord, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadStringRecord, _types.DifferentSpreadStringRecord, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadStringRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadStringRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadStringRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4370,11 +4472,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadFloatRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadFloatRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4398,14 +4502,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadFloatRecord, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadFloatRecord, _types.DifferentSpreadFloatRecord, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadFloatRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadFloatRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadFloatRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4546,11 +4651,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadModelRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4574,14 +4681,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadModelRecord, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadModelRecord, _types.DifferentSpreadModelRecord, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelRecord or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadModelRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelRecord or + ~typetest.property.additionalproperties.types.DifferentSpreadModelRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4722,11 +4830,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadModelArrayRecord, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4750,14 +4860,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadModelArrayRecord, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadModelArrayRecord, _types.DifferentSpreadModelArrayRecord, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelArrayRecord, JSON, - IO[bytes] Required. + :param body: body. Is either a DifferentSpreadModelArrayRecord type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelArrayRecord or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4898,11 +5010,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadStringDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadStringDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4926,14 +5040,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadStringDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadStringDerived, _types.DifferentSpreadStringDerived, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadStringDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadStringDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadStringDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadStringDerived or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5074,11 +5189,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadFloatDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadFloatDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5102,14 +5219,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadFloatDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadFloatDerived, _types.DifferentSpreadFloatDerived, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadFloatDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadFloatDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadFloatDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadFloatDerived or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5250,11 +5368,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadModelDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5278,14 +5398,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadModelDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadModelDerived, _types.DifferentSpreadModelDerived, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelDerived, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelDerived or JSON - or IO[bytes] + :param body: body. Is either a DifferentSpreadModelDerived type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelDerived or + ~typetest.property.additionalproperties.types.DifferentSpreadModelDerived or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5426,11 +5547,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DifferentSpreadModelArrayDerived, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayDerived :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5454,14 +5577,16 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DifferentSpreadModelArrayDerived, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.DifferentSpreadModelArrayDerived, _types.DifferentSpreadModelArrayDerived, IO[bytes]], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: DifferentSpreadModelArrayDerived, JSON, - IO[bytes] Required. + :param body: body. Is either a DifferentSpreadModelArrayDerived type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.DifferentSpreadModelArrayDerived or - JSON or IO[bytes] + ~typetest.property.additionalproperties.types.DifferentSpreadModelArrayDerived or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5599,11 +5724,11 @@ def put(self, body: _models.MultipleSpreadRecord, *, content_type: str = "applic """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.MultipleSpreadRecord, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.MultipleSpreadRecord :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5627,14 +5752,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.MultipleSpreadRecord, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.MultipleSpreadRecord, _types.MultipleSpreadRecord, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: MultipleSpreadRecord, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.MultipleSpreadRecord or JSON or - IO[bytes] + :param body: body. Is either a MultipleSpreadRecord type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.MultipleSpreadRecord or + ~typetest.property.additionalproperties.types.MultipleSpreadRecord or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5772,11 +5896,11 @@ def put(self, body: _models.SpreadRecordForUnion, *, content_type: str = "applic """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.SpreadRecordForUnion, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForUnion :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5800,14 +5924,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadRecordForUnion, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.SpreadRecordForUnion, _types.SpreadRecordForUnion, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForUnion, JSON, IO[bytes] - Required. - :type body: ~typetest.property.additionalproperties.models.SpreadRecordForUnion or JSON or - IO[bytes] + :param body: body. Is either a SpreadRecordForUnion type or a IO[bytes] type. Required. + :type body: ~typetest.property.additionalproperties.models.SpreadRecordForUnion or + ~typetest.property.additionalproperties.types.SpreadRecordForUnion or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5952,11 +6075,17 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5980,14 +6109,19 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion, _types.SpreadRecordForNonDiscriminatedUnion, IO[bytes] + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion type or a IO[bytes] type. + Required. :type body: ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion - or JSON or IO[bytes] + or ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion or + IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -6133,11 +6267,17 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion2, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -6161,14 +6301,19 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion2, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion2, _types.SpreadRecordForNonDiscriminatedUnion2, IO[bytes] + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion2, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion2 type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion2 or JSON or + ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion2 or + ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion2 or IO[bytes] :return: None :rtype: None @@ -6315,11 +6460,17 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, + body: _types.SpreadRecordForNonDiscriminatedUnion3, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -6343,14 +6494,19 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.SpreadRecordForNonDiscriminatedUnion3, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[ + _models.SpreadRecordForNonDiscriminatedUnion3, _types.SpreadRecordForNonDiscriminatedUnion3, IO[bytes] + ], + **kwargs: Any, ) -> None: """Put operation. - :param body: body. Is one of the following types: SpreadRecordForNonDiscriminatedUnion3, JSON, - IO[bytes] Required. + :param body: body. Is either a SpreadRecordForNonDiscriminatedUnion3 type or a IO[bytes] type. + Required. :type body: - ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion3 or JSON or + ~typetest.property.additionalproperties.models.SpreadRecordForNonDiscriminatedUnion3 or + ~typetest.property.additionalproperties.types.SpreadRecordForNonDiscriminatedUnion3 or IO[bytes] :return: None :rtype: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/types.py index e55e1d5ebcb8..52905ff06c42 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-additionalproperties/typetest/property/additionalproperties/types.py @@ -1,6 +1,5 @@ # coding=utf-8 -import datetime from typing import Literal, Union from typing_extensions import Required, TypedDict @@ -48,7 +47,7 @@ class DifferentSpreadModelArrayDerived(DifferentSpreadModelArrayRecord): :ivar known_prop: Required. :vartype known_prop: str :ivar derived_prop: The index property. Required. - :vartype derived_prop: list[~typetest.property.additionalproperties.models.ModelForRecord] + :vartype derived_prop: list["ModelForRecord"] """ derivedProp: Required[list["ModelForRecord"]] @@ -73,7 +72,7 @@ class DifferentSpreadModelDerived(DifferentSpreadModelRecord): :ivar known_prop: Required. :vartype known_prop: str :ivar derived_prop: The index property. Required. - :vartype derived_prop: ~typetest.property.additionalproperties.models.ModelForRecord + :vartype derived_prop: "ModelForRecord" """ derivedProp: Required["ModelForRecord"] @@ -120,7 +119,7 @@ class ExtendsModelAdditionalProperties(TypedDict, total=False): """The model extends from Record type. :ivar known_prop: Required. - :vartype known_prop: ~typetest.property.additionalproperties.models.ModelForRecord + :vartype known_prop: "ModelForRecord" """ knownProp: Required["ModelForRecord"] @@ -131,7 +130,7 @@ class ExtendsModelArrayAdditionalProperties(TypedDict, total=False): """The model extends from Record type. :ivar known_prop: Required. - :vartype known_prop: list[~typetest.property.additionalproperties.models.ModelForRecord] + :vartype known_prop: list["ModelForRecord"] """ knownProp: Required[list["ModelForRecord"]] @@ -183,7 +182,7 @@ class ExtendsUnknownAdditionalPropertiesDiscriminatedDerived(TypedDict, total=Fa :ivar name: The name property. Required. :vartype name: str :ivar kind: Required. Default value is "derived". - :vartype kind: str + :vartype kind: Literal["derived"] :ivar index: The index property. Required. :vartype index: int :ivar age: The age property. @@ -215,7 +214,7 @@ class IsModelAdditionalProperties(TypedDict, total=False): """The model is from Record type. :ivar known_prop: Required. - :vartype known_prop: ~typetest.property.additionalproperties.models.ModelForRecord + :vartype known_prop: "ModelForRecord" """ knownProp: Required["ModelForRecord"] @@ -226,7 +225,7 @@ class IsModelArrayAdditionalProperties(TypedDict, total=False): """The model is from Record type. :ivar known_prop: Required. - :vartype known_prop: list[~typetest.property.additionalproperties.models.ModelForRecord] + :vartype known_prop: list["ModelForRecord"] """ knownProp: Required[list["ModelForRecord"]] @@ -278,7 +277,7 @@ class IsUnknownAdditionalPropertiesDiscriminatedDerived(TypedDict, total=False): :ivar name: The name property. Required. :vartype name: str :ivar kind: Required. Default value is "derived". - :vartype kind: str + :vartype kind: Literal["derived"] :ivar index: The index property. Required. :vartype index: int :ivar age: The age property. @@ -332,7 +331,7 @@ class SpreadModelArrayRecord(TypedDict, total=False): """SpreadModelArrayRecord. :ivar known_prop: Required. - :vartype known_prop: list[~typetest.property.additionalproperties.models.ModelForRecord] + :vartype known_prop: list["ModelForRecord"] """ knownProp: Required[list["ModelForRecord"]] @@ -343,7 +342,7 @@ class SpreadModelRecord(TypedDict, total=False): """The model spread Record with the same known property type. :ivar known_prop: Required. - :vartype known_prop: ~typetest.property.additionalproperties.models.ModelForRecord + :vartype known_prop: "ModelForRecord" """ knownProp: Required["ModelForRecord"] @@ -409,7 +408,7 @@ class WidgetData0(TypedDict, total=False): """WidgetData0. :ivar kind: Required. Default value is "kind0". - :vartype kind: str + :vartype kind: Literal["kind0"] :ivar foo_prop: Required. :vartype foo_prop: str """ @@ -424,25 +423,25 @@ class WidgetData1(TypedDict, total=False): """WidgetData1. :ivar kind: Required. Default value is "kind1". - :vartype kind: str + :vartype kind: Literal["kind1"] :ivar start: Required. - :vartype start: ~datetime.datetime + :vartype start: str :ivar end: - :vartype end: ~datetime.datetime + :vartype end: str """ kind: Required[Literal["kind1"]] """Required. Default value is \"kind1\".""" - start: Required[datetime.datetime] + start: Required[str] """Required.""" - end: datetime.datetime + end: str class WidgetData2(TypedDict, total=False): """WidgetData2. :ivar kind: Required. Default value is "kind1". - :vartype kind: str + :vartype kind: Literal["kind1"] :ivar start: Required. :vartype start: str """ diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/pyproject.toml index 271a3ff524b0..174114831df8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/operations/_operations.py index df7c4fe7e380..c6daac5aeb28 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/operations/_operations.py @@ -20,7 +20,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -55,7 +55,6 @@ ) from .._configuration import NullableClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -203,12 +202,12 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.StringProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -233,11 +232,14 @@ async def patch_non_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_non_null(self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_non_null( + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.StringProperty or + ~typetest.property.nullable.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -304,12 +306,12 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.StringProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -334,11 +336,14 @@ async def patch_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_null(self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.StringProperty or + ~typetest.property.nullable.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -531,12 +536,12 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.BytesProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -561,11 +566,14 @@ async def patch_non_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_non_null(self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_non_null( + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.BytesProperty or + ~typetest.property.nullable.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -632,12 +640,12 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.BytesProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -662,11 +670,14 @@ async def patch_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_null(self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.BytesProperty or + ~typetest.property.nullable.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -859,12 +870,12 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.DatetimeProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -889,11 +900,14 @@ async def patch_non_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_non_null(self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_non_null( + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DatetimeProperty or + ~typetest.property.nullable.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -960,12 +974,12 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.DatetimeProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -990,11 +1004,14 @@ async def patch_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_null(self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DatetimeProperty or + ~typetest.property.nullable.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1187,12 +1204,12 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.DurationProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1217,11 +1234,14 @@ async def patch_non_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_non_null(self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_non_null( + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DurationProperty or + ~typetest.property.nullable.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1288,12 +1308,12 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.DurationProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1318,11 +1338,14 @@ async def patch_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_null(self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DurationProperty or + ~typetest.property.nullable.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1519,12 +1542,12 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1550,12 +1573,13 @@ async def patch_non_null( """ async def patch_non_null( - self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsByteProperty or + ~typetest.property.nullable.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1626,12 +1650,12 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1656,11 +1680,14 @@ async def patch_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_null(self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsByteProperty or + ~typetest.property.nullable.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1859,12 +1886,16 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: _types.CollectionsModelProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1890,12 +1921,13 @@ async def patch_non_null( """ async def patch_non_null( - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsModelProperty or + ~typetest.property.nullable.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1966,12 +1998,16 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: _types.CollectionsModelProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1996,11 +2032,14 @@ async def patch_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_null(self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsModelProperty or + ~typetest.property.nullable.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2199,12 +2238,16 @@ async def patch_non_null( @overload async def patch_non_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: _types.CollectionsStringProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2230,13 +2273,13 @@ async def patch_non_null( """ async def patch_non_null( - self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.nullable.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsStringProperty or + ~typetest.property.nullable.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2307,12 +2350,16 @@ async def patch_null( @overload async def patch_null( - self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + body: _types.CollectionsStringProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2337,12 +2384,14 @@ async def patch_null( :raises ~corehttp.exceptions.HttpResponseError: """ - async def patch_null(self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def patch_null( + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.nullable.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsStringProperty or + ~typetest.property.nullable.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/operations/_operations.py index 75f2a0f84792..f561574fb1e3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/operations/_operations.py @@ -20,12 +20,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import NullableClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -567,11 +566,13 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, body: _types.StringProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -597,12 +598,13 @@ def patch_non_null( """ def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.StringProperty or + ~typetest.property.nullable.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -668,11 +670,13 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, body: _types.StringProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -696,12 +700,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- """ def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.StringProperty or + ~typetest.property.nullable.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -893,11 +898,13 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, body: _types.BytesProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -923,12 +930,13 @@ def patch_non_null( """ def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.BytesProperty or + ~typetest.property.nullable.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -994,11 +1002,13 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, body: _types.BytesProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1022,12 +1032,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- """ def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.BytesProperty or + ~typetest.property.nullable.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1219,11 +1230,13 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, body: _types.DatetimeProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1249,12 +1262,13 @@ def patch_non_null( """ def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DatetimeProperty or + ~typetest.property.nullable.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1320,11 +1334,13 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, body: _types.DatetimeProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1348,12 +1364,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- """ def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DatetimeProperty or + ~typetest.property.nullable.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1545,11 +1562,13 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, body: _types.DurationProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1575,12 +1594,13 @@ def patch_non_null( """ def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DurationProperty or + ~typetest.property.nullable.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1646,11 +1666,13 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, body: _types.DurationProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1674,12 +1696,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- """ def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.DurationProperty or + ~typetest.property.nullable.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1875,11 +1898,13 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1905,12 +1930,13 @@ def patch_non_null( """ def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsByteProperty or + ~typetest.property.nullable.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1980,11 +2006,13 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2008,12 +2036,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- """ def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsByteProperty or + ~typetest.property.nullable.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2211,11 +2240,17 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, + body: _types.CollectionsModelProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2241,12 +2276,13 @@ def patch_non_null( """ def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsModelProperty or + ~typetest.property.nullable.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2316,11 +2352,17 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, + body: _types.CollectionsModelProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2344,12 +2386,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- """ def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.nullable.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsModelProperty or + ~typetest.property.nullable.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2547,11 +2590,17 @@ def patch_non_null( """ @overload - def patch_non_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_non_null( + self, + body: _types.CollectionsStringProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2577,13 +2626,13 @@ def patch_non_null( """ def patch_non_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.nullable.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsStringProperty or + ~typetest.property.nullable.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2653,11 +2702,17 @@ def patch_null( """ @overload - def patch_null(self, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any) -> None: + def patch_null( + self, + body: _types.CollectionsStringProperty, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.nullable.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2681,13 +2736,13 @@ def patch_null(self, body: IO[bytes], *, content_type: str = "application/merge- """ def patch_null( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.nullable.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.nullable.models.CollectionsStringProperty or + ~typetest.property.nullable.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/types.py index f63c5f7736ab..3c3d7a895128 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-nullable/typetest/property/nullable/types.py @@ -1,6 +1,5 @@ # coding=utf-8 -import datetime from typing import Optional from typing_extensions import Required, TypedDict @@ -12,12 +11,12 @@ class BytesProperty(TypedDict, total=False): :ivar required_property: Required property. Required. :vartype required_property: str :ivar nullable_property: Property. Required. - :vartype nullable_property: bytes + :vartype nullable_property: str """ requiredProperty: Required[str] """Required property. Required.""" - nullableProperty: Required[Optional[bytes]] + nullableProperty: Required[Optional[str]] """Property. Required.""" @@ -27,12 +26,12 @@ class CollectionsByteProperty(TypedDict, total=False): :ivar required_property: Required property. Required. :vartype required_property: str :ivar nullable_property: Property. Required. - :vartype nullable_property: list[bytes] + :vartype nullable_property: list[str] """ requiredProperty: Required[str] """Required property. Required.""" - nullableProperty: Required[Optional[list[bytes]]] + nullableProperty: Required[Optional[list[str]]] """Property. Required.""" @@ -42,7 +41,7 @@ class CollectionsModelProperty(TypedDict, total=False): :ivar required_property: Required property. Required. :vartype required_property: str :ivar nullable_property: Property. Required. - :vartype nullable_property: list[~typetest.property.nullable.models.InnerModel] + :vartype nullable_property: list["InnerModel"] """ requiredProperty: Required[str] @@ -72,12 +71,12 @@ class DatetimeProperty(TypedDict, total=False): :ivar required_property: Required property. Required. :vartype required_property: str :ivar nullable_property: Property. Required. - :vartype nullable_property: ~datetime.datetime + :vartype nullable_property: str """ requiredProperty: Required[str] """Required property. Required.""" - nullableProperty: Required[Optional[datetime.datetime]] + nullableProperty: Required[Optional[str]] """Property. Required.""" @@ -87,12 +86,12 @@ class DurationProperty(TypedDict, total=False): :ivar required_property: Required property. Required. :vartype required_property: str :ivar nullable_property: Property. Required. - :vartype nullable_property: ~datetime.timedelta + :vartype nullable_property: str """ requiredProperty: Required[str] """Required property. Required.""" - nullableProperty: Required[Optional[datetime.timedelta]] + nullableProperty: Required[Optional[str]] """Property. Required.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/pyproject.toml index f59adf70bd52..93b8a015f8b1 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/operations/_operations.py index 1f6e2b2cbb1a..a3e383009061 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/operations/_operations.py @@ -20,7 +20,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -91,7 +91,6 @@ ) from .._configuration import OptionalClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -238,11 +237,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -265,11 +266,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringProperty or + ~typetest.property.optional.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -335,11 +339,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -362,11 +368,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringProperty or + ~typetest.property.optional.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -558,11 +567,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -585,11 +596,12 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all(self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BytesProperty or + ~typetest.property.optional.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -655,11 +667,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -682,11 +696,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BytesProperty or + ~typetest.property.optional.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -878,11 +895,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -905,11 +924,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DatetimeProperty or + ~typetest.property.optional.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -975,11 +997,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1002,11 +1026,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DatetimeProperty or + ~typetest.property.optional.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1198,11 +1225,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1225,11 +1254,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DurationProperty or + ~typetest.property.optional.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1295,11 +1327,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1322,11 +1356,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DurationProperty or + ~typetest.property.optional.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1518,11 +1555,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.PlainDateProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainDateProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1545,11 +1584,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.PlainDateProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.PlainDateProperty, _types.PlainDateProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: PlainDateProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainDateProperty or JSON or IO[bytes] + :param body: Is either a PlainDateProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainDateProperty or + ~typetest.property.optional.types.PlainDateProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1615,11 +1657,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.PlainDateProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainDateProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1642,11 +1686,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.PlainDateProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.PlainDateProperty, _types.PlainDateProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: PlainDateProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainDateProperty or JSON or IO[bytes] + :param body: Is either a PlainDateProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainDateProperty or + ~typetest.property.optional.types.PlainDateProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1838,11 +1885,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.PlainTimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainTimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1865,11 +1914,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.PlainTimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.PlainTimeProperty, _types.PlainTimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: PlainTimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainTimeProperty or JSON or IO[bytes] + :param body: Is either a PlainTimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainTimeProperty or + ~typetest.property.optional.types.PlainTimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1935,11 +1987,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.PlainTimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainTimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1962,11 +2016,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.PlainTimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.PlainTimeProperty, _types.PlainTimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: PlainTimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainTimeProperty or JSON or IO[bytes] + :param body: Is either a PlainTimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainTimeProperty or + ~typetest.property.optional.types.PlainTimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2158,11 +2215,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2185,11 +2244,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsByteProperty or + ~typetest.property.optional.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2255,11 +2317,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2282,11 +2346,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsByteProperty or + ~typetest.property.optional.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2480,11 +2547,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2507,11 +2576,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsModelProperty or + ~typetest.property.optional.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2577,11 +2649,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2604,11 +2678,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsModelProperty or + ~typetest.property.optional.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2800,11 +2877,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2827,11 +2906,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringLiteralProperty or JSON or IO[bytes] + :param body: Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringLiteralProperty or + ~typetest.property.optional.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2897,11 +2979,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2924,11 +3008,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringLiteralProperty or JSON or IO[bytes] + :param body: Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringLiteralProperty or + ~typetest.property.optional.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3120,11 +3207,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3147,11 +3236,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.IntLiteralProperty or JSON or IO[bytes] + :param body: Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.IntLiteralProperty or + ~typetest.property.optional.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3217,11 +3309,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3244,11 +3338,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.IntLiteralProperty or JSON or IO[bytes] + :param body: Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.IntLiteralProperty or + ~typetest.property.optional.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3440,11 +3537,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3467,11 +3566,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.FloatLiteralProperty or + ~typetest.property.optional.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3537,11 +3639,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3564,11 +3668,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.FloatLiteralProperty or + ~typetest.property.optional.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3760,11 +3867,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3787,11 +3896,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BooleanLiteralProperty or + ~typetest.property.optional.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3857,11 +3969,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3884,11 +3998,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BooleanLiteralProperty or + ~typetest.property.optional.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4082,11 +4199,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4109,12 +4228,16 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or + ~typetest.property.optional.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4180,11 +4303,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4208,13 +4333,15 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application """ async def put_default( - self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or + ~typetest.property.optional.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4406,11 +4533,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4433,11 +4562,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or + ~typetest.property.optional.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4503,11 +4635,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4530,11 +4664,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or + ~typetest.property.optional.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4728,11 +4865,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4755,12 +4894,14 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or + ~typetest.property.optional.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4826,11 +4967,13 @@ async def put_default( """ @overload - async def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_default( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4853,12 +4996,14 @@ async def put_default(self, body: IO[bytes], *, content_type: str = "application :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_default(self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_default( + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or + ~typetest.property.optional.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5052,11 +5197,13 @@ async def put_all( """ @overload - async def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_all( + self, body: _types.RequiredAndOptionalProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.RequiredAndOptionalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5079,12 +5226,16 @@ async def put_all(self, body: IO[bytes], *, content_type: str = "application/jso :raises ~corehttp.exceptions.HttpResponseError: """ - async def put_all(self, body: Union[_models.RequiredAndOptionalProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put_all( + self, + body: Union[_models.RequiredAndOptionalProperty, _types.RequiredAndOptionalProperty, IO[bytes]], + **kwargs: Any + ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: RequiredAndOptionalProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or JSON or IO[bytes] + :param body: Is either a RequiredAndOptionalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or + ~typetest.property.optional.types.RequiredAndOptionalProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5150,11 +5301,13 @@ async def put_required_only( """ @overload - async def put_required_only(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put_required_only( + self, body: _types.RequiredAndOptionalProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with only required properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.RequiredAndOptionalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5180,13 +5333,15 @@ async def put_required_only( """ async def put_required_only( - self, body: Union[_models.RequiredAndOptionalProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.RequiredAndOptionalProperty, _types.RequiredAndOptionalProperty, IO[bytes]], + **kwargs: Any ) -> None: """Put a body with only required properties. - :param body: Is one of the following types: RequiredAndOptionalProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or JSON or IO[bytes] + :param body: Is either a RequiredAndOptionalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or + ~typetest.property.optional.types.RequiredAndOptionalProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/operations/_operations.py index 4afbcb0dbe5e..5dbea29238cf 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/operations/_operations.py @@ -20,12 +20,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import OptionalClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -1073,11 +1072,11 @@ def put_all(self, body: _models.StringProperty, *, content_type: str = "applicat """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1101,12 +1100,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringProperty or + ~typetest.property.optional.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1172,11 +1172,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1200,12 +1202,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringProperty or JSON or IO[bytes] + :param body: Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringProperty or + ~typetest.property.optional.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1395,11 +1398,11 @@ def put_all(self, body: _models.BytesProperty, *, content_type: str = "applicati """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1423,12 +1426,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BytesProperty or + ~typetest.property.optional.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1494,11 +1498,11 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default(self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1522,12 +1526,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BytesProperty or JSON or IO[bytes] + :param body: Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BytesProperty or + ~typetest.property.optional.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1717,11 +1722,11 @@ def put_all(self, body: _models.DatetimeProperty, *, content_type: str = "applic """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1745,12 +1750,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DatetimeProperty or + ~typetest.property.optional.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1816,11 +1822,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1844,12 +1852,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DatetimeProperty or JSON or IO[bytes] + :param body: Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DatetimeProperty or + ~typetest.property.optional.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2039,11 +2048,11 @@ def put_all(self, body: _models.DurationProperty, *, content_type: str = "applic """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2067,12 +2076,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DurationProperty or + ~typetest.property.optional.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2138,11 +2148,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2166,12 +2178,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.DurationProperty or JSON or IO[bytes] + :param body: Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.DurationProperty or + ~typetest.property.optional.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2363,11 +2376,11 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.PlainDateProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainDateProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2391,12 +2404,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PlainDateProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.PlainDateProperty, _types.PlainDateProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: PlainDateProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainDateProperty or JSON or IO[bytes] + :param body: Is either a PlainDateProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainDateProperty or + ~typetest.property.optional.types.PlainDateProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2462,11 +2476,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.PlainDateProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainDateProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2490,12 +2506,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PlainDateProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.PlainDateProperty, _types.PlainDateProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: PlainDateProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainDateProperty or JSON or IO[bytes] + :param body: Is either a PlainDateProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainDateProperty or + ~typetest.property.optional.types.PlainDateProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2687,11 +2704,11 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all(self, body: _types.PlainTimeProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainTimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2715,12 +2732,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PlainTimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.PlainTimeProperty, _types.PlainTimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: PlainTimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainTimeProperty or JSON or IO[bytes] + :param body: Is either a PlainTimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainTimeProperty or + ~typetest.property.optional.types.PlainTimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2786,11 +2804,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.PlainTimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.PlainTimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2814,12 +2834,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PlainTimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.PlainTimeProperty, _types.PlainTimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: PlainTimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.PlainTimeProperty or JSON or IO[bytes] + :param body: Is either a PlainTimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.PlainTimeProperty or + ~typetest.property.optional.types.PlainTimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3011,11 +3032,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3039,12 +3062,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsByteProperty or + ~typetest.property.optional.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3110,11 +3134,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.CollectionsByteProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsByteProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3138,12 +3164,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsByteProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsByteProperty, _types.CollectionsByteProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsByteProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsByteProperty or JSON or IO[bytes] + :param body: Is either a CollectionsByteProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsByteProperty or + ~typetest.property.optional.types.CollectionsByteProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3337,11 +3364,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3365,12 +3394,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsModelProperty or + ~typetest.property.optional.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3436,11 +3466,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3464,12 +3496,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.CollectionsModelProperty or + ~typetest.property.optional.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3661,11 +3694,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3689,12 +3724,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: StringLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringLiteralProperty or JSON or IO[bytes] + :param body: Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringLiteralProperty or + ~typetest.property.optional.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3760,11 +3796,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3788,12 +3826,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: StringLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.StringLiteralProperty or JSON or IO[bytes] + :param body: Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.StringLiteralProperty or + ~typetest.property.optional.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3985,11 +4024,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4013,12 +4054,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.IntLiteralProperty or JSON or IO[bytes] + :param body: Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.IntLiteralProperty or + ~typetest.property.optional.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4084,11 +4126,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4112,12 +4156,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.IntLiteralProperty or JSON or IO[bytes] + :param body: Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.IntLiteralProperty or + ~typetest.property.optional.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4309,11 +4354,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4337,12 +4384,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.FloatLiteralProperty or + ~typetest.property.optional.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4408,11 +4456,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4436,12 +4486,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.FloatLiteralProperty or + ~typetest.property.optional.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4633,11 +4684,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4661,12 +4714,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BooleanLiteralProperty or + ~typetest.property.optional.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4732,11 +4786,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4760,12 +4816,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.BooleanLiteralProperty or + ~typetest.property.optional.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4959,11 +5016,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4987,13 +5046,15 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any, ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or + ~typetest.property.optional.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5059,11 +5120,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5087,13 +5150,15 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any, ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionStringLiteralProperty or + ~typetest.property.optional.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5285,11 +5350,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5313,12 +5380,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or + ~typetest.property.optional.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5384,11 +5452,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5412,12 +5482,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionIntLiteralProperty or + ~typetest.property.optional.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5611,11 +5682,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5639,13 +5712,13 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or + ~typetest.property.optional.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5711,11 +5784,13 @@ def put_default( """ @overload - def put_default(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_default( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with default properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5739,13 +5814,13 @@ def put_default(self, body: IO[bytes], *, content_type: str = "application/json" """ def put_default( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put a body with default properties. - :param body: Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.UnionFloatLiteralProperty or + ~typetest.property.optional.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5939,11 +6014,13 @@ def put_all( """ @overload - def put_all(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_all( + self, body: _types.RequiredAndOptionalProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with all properties present. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.RequiredAndOptionalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5967,13 +6044,15 @@ def put_all(self, body: IO[bytes], *, content_type: str = "application/json", ** """ def put_all( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.RequiredAndOptionalProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.RequiredAndOptionalProperty, _types.RequiredAndOptionalProperty, IO[bytes]], + **kwargs: Any, ) -> None: """Put a body with all properties present. - :param body: Is one of the following types: RequiredAndOptionalProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or JSON or IO[bytes] + :param body: Is either a RequiredAndOptionalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or + ~typetest.property.optional.types.RequiredAndOptionalProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -6039,11 +6118,13 @@ def put_required_only( """ @overload - def put_required_only(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put_required_only( + self, body: _types.RequiredAndOptionalProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put a body with only required properties. :param body: Required. - :type body: JSON + :type body: ~typetest.property.optional.types.RequiredAndOptionalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -6067,13 +6148,15 @@ def put_required_only(self, body: IO[bytes], *, content_type: str = "application """ def put_required_only( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.RequiredAndOptionalProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.RequiredAndOptionalProperty, _types.RequiredAndOptionalProperty, IO[bytes]], + **kwargs: Any, ) -> None: """Put a body with only required properties. - :param body: Is one of the following types: RequiredAndOptionalProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or JSON or IO[bytes] + :param body: Is either a RequiredAndOptionalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.optional.models.RequiredAndOptionalProperty or + ~typetest.property.optional.types.RequiredAndOptionalProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/types.py index c87018e2008d..4df82efd9216 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-optional/typetest/property/optional/types.py @@ -1,6 +1,5 @@ # coding=utf-8 -import datetime from typing import Literal from typing_extensions import Required, TypedDict @@ -9,7 +8,7 @@ class BooleanLiteralProperty(TypedDict, total=False): """Model with boolean literal property. :ivar property: Property. Default value is True. - :vartype property: bool + :vartype property: Literal[True] """ property: Literal[True] @@ -21,10 +20,10 @@ class BytesProperty(TypedDict, total=False): are looking for. :ivar property: Property. - :vartype property: bytes + :vartype property: str """ - property: bytes + property: str """Property.""" @@ -32,10 +31,10 @@ class CollectionsByteProperty(TypedDict, total=False): """Model with collection bytes properties. :ivar property: Property. - :vartype property: list[bytes] + :vartype property: list[str] """ - property: list[bytes] + property: list[str] """Property.""" @@ -43,7 +42,7 @@ class CollectionsModelProperty(TypedDict, total=False): """Model with collection models properties. :ivar property: Property. - :vartype property: list[~typetest.property.optional.models.StringProperty] + :vartype property: list["StringProperty"] """ property: list["StringProperty"] @@ -54,10 +53,10 @@ class DatetimeProperty(TypedDict, total=False): """Model with a datetime property. :ivar property: Property. - :vartype property: ~datetime.datetime + :vartype property: str """ - property: datetime.datetime + property: str """Property.""" @@ -65,10 +64,10 @@ class DurationProperty(TypedDict, total=False): """Model with a duration property. :ivar property: Property. - :vartype property: ~datetime.timedelta + :vartype property: str """ - property: datetime.timedelta + property: str """Property.""" @@ -87,7 +86,7 @@ class IntLiteralProperty(TypedDict, total=False): """Model with int literal property. :ivar property: Property. Default value is 1. - :vartype property: int + :vartype property: Literal[1] """ property: Literal[1] @@ -98,10 +97,10 @@ class PlainDateProperty(TypedDict, total=False): """Model with a plainDate property. :ivar property: Property. - :vartype property: ~datetime.date + :vartype property: str """ - property: datetime.date + property: str """Property.""" @@ -109,10 +108,10 @@ class PlainTimeProperty(TypedDict, total=False): """Model with a plainTime property. :ivar property: Property. - :vartype property: ~datetime.time + :vartype property: str """ - property: datetime.time + property: str """Property.""" @@ -135,7 +134,7 @@ class StringLiteralProperty(TypedDict, total=False): """Model with string literal property. :ivar property: Property. Default value is "hello". - :vartype property: str + :vartype property: Literal["hello"] """ property: Literal["hello"] @@ -158,7 +157,7 @@ class UnionFloatLiteralProperty(TypedDict, total=False): """Model with union of float literal property. :ivar property: Property. Is one of the following types: float - :vartype property: float or float + :vartype property: float """ property: float @@ -169,7 +168,7 @@ class UnionIntLiteralProperty(TypedDict, total=False): """Model with union of int literal property. :ivar property: Property. Is either a Literal[1] type or a Literal[2] type. - :vartype property: int or int + :vartype property: Literal[1, 2] """ property: Literal[1, 2] @@ -180,7 +179,7 @@ class UnionStringLiteralProperty(TypedDict, total=False): """Model with union of string literal property. :ivar property: Property. Is either a Literal["hello"] type or a Literal["world"] type. - :vartype property: str or str + :vartype property: Literal["hello", "world"] """ property: Literal["hello", "world"] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/pyproject.toml index c3456d8c5c49..2dd14801e60e 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_operations.py index 03b1d1b22a5e..72251060a042 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_operations.py @@ -20,7 +20,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -85,7 +85,6 @@ ) from .._configuration import ValueTypesClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -178,11 +177,11 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.BooleanProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BooleanProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -205,11 +204,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.BooleanProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.BooleanProperty, _types.BooleanProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: BooleanProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.BooleanProperty or JSON or IO[bytes] + :param body: body. Is either a BooleanProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BooleanProperty or + ~typetest.property.valuetypes.types.BooleanProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -345,11 +345,11 @@ async def put(self, body: _models.StringProperty, *, content_type: str = "applic """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -372,11 +372,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.StringProperty or JSON or IO[bytes] + :param body: body. Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.StringProperty or + ~typetest.property.valuetypes.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -512,11 +513,11 @@ async def put(self, body: _models.BytesProperty, *, content_type: str = "applica """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -539,11 +540,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.BytesProperty or JSON or IO[bytes] + :param body: body. Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BytesProperty or + ~typetest.property.valuetypes.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -679,11 +681,11 @@ async def put(self, body: _models.IntProperty, *, content_type: str = "applicati """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.IntProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.IntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -706,11 +708,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.IntProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.IntProperty, _types.IntProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: IntProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.IntProperty or JSON or IO[bytes] + :param body: body. Is either a IntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.IntProperty or + ~typetest.property.valuetypes.types.IntProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -846,11 +849,11 @@ async def put(self, body: _models.FloatProperty, *, content_type: str = "applica """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.FloatProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.FloatProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -873,11 +876,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.FloatProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.FloatProperty, _types.FloatProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: FloatProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.FloatProperty or JSON or IO[bytes] + :param body: body. Is either a FloatProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.FloatProperty or + ~typetest.property.valuetypes.types.FloatProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1015,11 +1019,11 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.DecimalProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DecimalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1042,11 +1046,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DecimalProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.DecimalProperty, _types.DecimalProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: DecimalProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DecimalProperty or JSON or IO[bytes] + :param body: body. Is either a DecimalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DecimalProperty or + ~typetest.property.valuetypes.types.DecimalProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1184,11 +1189,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.Decimal128Property, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.Decimal128Property :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1211,11 +1218,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.Decimal128Property, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.Decimal128Property, _types.Decimal128Property, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: Decimal128Property, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.Decimal128Property or JSON or IO[bytes] + :param body: body. Is either a Decimal128Property type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.Decimal128Property or + ~typetest.property.valuetypes.types.Decimal128Property or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1353,11 +1363,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1380,11 +1392,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DatetimeProperty or JSON or IO[bytes] + :param body: body. Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DatetimeProperty or + ~typetest.property.valuetypes.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1522,11 +1537,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1549,11 +1566,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DurationProperty or JSON or IO[bytes] + :param body: body. Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DurationProperty or + ~typetest.property.valuetypes.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1689,11 +1709,11 @@ async def put(self, body: _models.EnumProperty, *, content_type: str = "applicat """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.EnumProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.EnumProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1716,11 +1736,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.EnumProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.EnumProperty, _types.EnumProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: EnumProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.EnumProperty or JSON or IO[bytes] + :param body: body. Is either a EnumProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.EnumProperty or + ~typetest.property.valuetypes.types.EnumProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1858,11 +1879,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.ExtensibleEnumProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.ExtensibleEnumProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1885,12 +1908,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.ExtensibleEnumProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.ExtensibleEnumProperty, _types.ExtensibleEnumProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtensibleEnumProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.ExtensibleEnumProperty or JSON or IO[bytes] + :param body: body. Is either a ExtensibleEnumProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.ExtensibleEnumProperty or + ~typetest.property.valuetypes.types.ExtensibleEnumProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2026,11 +2051,11 @@ async def put(self, body: _models.ModelProperty, *, content_type: str = "applica """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.ModelProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.ModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2053,11 +2078,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.ModelProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.ModelProperty, _types.ModelProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: ModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.ModelProperty or JSON or IO[bytes] + :param body: body. Is either a ModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.ModelProperty or + ~typetest.property.valuetypes.types.ModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2196,11 +2222,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.CollectionsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2223,12 +2251,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsStringProperty or + ~typetest.property.valuetypes.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2366,11 +2396,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.CollectionsIntProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsIntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2393,12 +2425,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.CollectionsIntProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.CollectionsIntProperty, _types.CollectionsIntProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsIntProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsIntProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsIntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsIntProperty or + ~typetest.property.valuetypes.types.CollectionsIntProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2537,11 +2571,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2564,12 +2600,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsModelProperty or + ~typetest.property.valuetypes.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2708,11 +2746,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.DictionaryStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DictionaryStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2735,12 +2775,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.DictionaryStringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.DictionaryStringProperty, _types.DictionaryStringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: DictionaryStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.DictionaryStringProperty or JSON or IO[bytes] + :param body: body. Is either a DictionaryStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DictionaryStringProperty or + ~typetest.property.valuetypes.types.DictionaryStringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2876,11 +2918,11 @@ async def put(self, body: _models.NeverProperty, *, content_type: str = "applica """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put(self, body: _types.NeverProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.NeverProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2903,11 +2945,12 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.NeverProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put(self, body: Union[_models.NeverProperty, _types.NeverProperty, IO[bytes]], **kwargs: Any) -> None: """Put operation. - :param body: body. Is one of the following types: NeverProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.NeverProperty or JSON or IO[bytes] + :param body: body. Is either a NeverProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.NeverProperty or + ~typetest.property.valuetypes.types.NeverProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3045,11 +3088,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnknownStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3072,12 +3117,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.UnknownStringProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnknownStringProperty, _types.UnknownStringProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownStringProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownStringProperty or + ~typetest.property.valuetypes.types.UnknownStringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3215,11 +3262,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnknownIntProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownIntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3242,11 +3291,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.UnknownIntProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnknownIntProperty, _types.UnknownIntProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownIntProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.UnknownIntProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownIntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownIntProperty or + ~typetest.property.valuetypes.types.UnknownIntProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3384,11 +3436,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnknownDictProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownDictProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3411,12 +3465,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.UnknownDictProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnknownDictProperty, _types.UnknownDictProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownDictProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownDictProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownDictProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownDictProperty or + ~typetest.property.valuetypes.types.UnknownDictProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3554,11 +3610,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnknownArrayProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3581,12 +3639,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.UnknownArrayProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnknownArrayProperty, _types.UnknownArrayProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownArrayProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownArrayProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownArrayProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownArrayProperty or + ~typetest.property.valuetypes.types.UnknownArrayProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3724,11 +3784,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3751,12 +3813,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: StringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.StringLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.StringLiteralProperty or + ~typetest.property.valuetypes.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3894,11 +3958,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3921,11 +3987,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.IntLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.IntLiteralProperty or + ~typetest.property.valuetypes.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4063,11 +4132,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4090,12 +4161,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.FloatLiteralProperty or + ~typetest.property.valuetypes.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4233,11 +4306,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4260,12 +4335,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BooleanLiteralProperty or + ~typetest.property.valuetypes.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4404,11 +4481,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4431,13 +4510,16 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionStringLiteralProperty or JSON or - IO[bytes] + :param body: body. Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionStringLiteralProperty or + ~typetest.property.valuetypes.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4575,11 +4657,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4602,12 +4686,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionIntLiteralProperty or + ~typetest.property.valuetypes.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4746,11 +4832,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4773,12 +4861,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionFloatLiteralProperty or + ~typetest.property.valuetypes.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4916,11 +5006,13 @@ async def put( """ @overload - async def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def put( + self, body: _types.UnionEnumValueProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionEnumValueProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4943,12 +5035,14 @@ async def put(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def put(self, body: Union[_models.UnionEnumValueProperty, JSON, IO[bytes]], **kwargs: Any) -> None: + async def put( + self, body: Union[_models.UnionEnumValueProperty, _types.UnionEnumValueProperty, IO[bytes]], **kwargs: Any + ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionEnumValueProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionEnumValueProperty or JSON or IO[bytes] + :param body: body. Is either a UnionEnumValueProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionEnumValueProperty or + ~typetest.property.valuetypes.types.UnionEnumValueProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/operations/_operations.py index 47172f51644c..b6b225fbaac7 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/operations/_operations.py @@ -20,12 +20,11 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import ValueTypesClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -931,11 +930,11 @@ def put(self, body: _models.BooleanProperty, *, content_type: str = "application """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.BooleanProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BooleanProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -959,12 +958,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BooleanProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BooleanProperty, _types.BooleanProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: BooleanProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.BooleanProperty or JSON or IO[bytes] + :param body: body. Is either a BooleanProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BooleanProperty or + ~typetest.property.valuetypes.types.BooleanProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1100,11 +1100,11 @@ def put(self, body: _models.StringProperty, *, content_type: str = "application/ """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.StringProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.StringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1128,12 +1128,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringProperty, _types.StringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: StringProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.StringProperty or JSON or IO[bytes] + :param body: body. Is either a StringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.StringProperty or + ~typetest.property.valuetypes.types.StringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1269,11 +1270,11 @@ def put(self, body: _models.BytesProperty, *, content_type: str = "application/j """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.BytesProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BytesProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1297,12 +1298,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BytesProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BytesProperty, _types.BytesProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: BytesProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.BytesProperty or JSON or IO[bytes] + :param body: body. Is either a BytesProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BytesProperty or + ~typetest.property.valuetypes.types.BytesProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1438,11 +1440,11 @@ def put(self, body: _models.IntProperty, *, content_type: str = "application/jso """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.IntProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.IntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1466,12 +1468,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IntProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.IntProperty, _types.IntProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: IntProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.IntProperty or JSON or IO[bytes] + :param body: body. Is either a IntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.IntProperty or + ~typetest.property.valuetypes.types.IntProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1607,11 +1610,11 @@ def put(self, body: _models.FloatProperty, *, content_type: str = "application/j """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.FloatProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.FloatProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1635,12 +1638,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FloatProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.FloatProperty, _types.FloatProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: FloatProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.FloatProperty or JSON or IO[bytes] + :param body: body. Is either a FloatProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.FloatProperty or + ~typetest.property.valuetypes.types.FloatProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1776,11 +1780,11 @@ def put(self, body: _models.DecimalProperty, *, content_type: str = "application """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.DecimalProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DecimalProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1804,12 +1808,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DecimalProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DecimalProperty, _types.DecimalProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: DecimalProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DecimalProperty or JSON or IO[bytes] + :param body: body. Is either a DecimalProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DecimalProperty or + ~typetest.property.valuetypes.types.DecimalProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -1945,11 +1950,11 @@ def put(self, body: _models.Decimal128Property, *, content_type: str = "applicat """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.Decimal128Property, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.Decimal128Property :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1973,12 +1978,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.Decimal128Property, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.Decimal128Property, _types.Decimal128Property, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: Decimal128Property, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.Decimal128Property or JSON or IO[bytes] + :param body: body. Is either a Decimal128Property type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.Decimal128Property or + ~typetest.property.valuetypes.types.Decimal128Property or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2114,11 +2120,11 @@ def put(self, body: _models.DatetimeProperty, *, content_type: str = "applicatio """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.DatetimeProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DatetimeProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2142,12 +2148,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DatetimeProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DatetimeProperty, _types.DatetimeProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: DatetimeProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DatetimeProperty or JSON or IO[bytes] + :param body: body. Is either a DatetimeProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DatetimeProperty or + ~typetest.property.valuetypes.types.DatetimeProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2283,11 +2290,11 @@ def put(self, body: _models.DurationProperty, *, content_type: str = "applicatio """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.DurationProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DurationProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2311,12 +2318,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DurationProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DurationProperty, _types.DurationProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: DurationProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.DurationProperty or JSON or IO[bytes] + :param body: body. Is either a DurationProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DurationProperty or + ~typetest.property.valuetypes.types.DurationProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2452,11 +2460,11 @@ def put(self, body: _models.EnumProperty, *, content_type: str = "application/js """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.EnumProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.EnumProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2480,12 +2488,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.EnumProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.EnumProperty, _types.EnumProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: EnumProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.EnumProperty or JSON or IO[bytes] + :param body: body. Is either a EnumProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.EnumProperty or + ~typetest.property.valuetypes.types.EnumProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2623,11 +2632,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.ExtensibleEnumProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.ExtensibleEnumProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2651,13 +2662,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ExtensibleEnumProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ExtensibleEnumProperty, _types.ExtensibleEnumProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: ExtensibleEnumProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.ExtensibleEnumProperty or JSON or IO[bytes] + :param body: body. Is either a ExtensibleEnumProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.ExtensibleEnumProperty or + ~typetest.property.valuetypes.types.ExtensibleEnumProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2793,11 +2804,11 @@ def put(self, body: _models.ModelProperty, *, content_type: str = "application/j """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.ModelProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.ModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2821,12 +2832,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.ModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.ModelProperty, _types.ModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: ModelProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.ModelProperty or JSON or IO[bytes] + :param body: body. Is either a ModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.ModelProperty or + ~typetest.property.valuetypes.types.ModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -2965,11 +2977,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.CollectionsStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2993,13 +3007,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsStringProperty, _types.CollectionsStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsStringProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsStringProperty or + ~typetest.property.valuetypes.types.CollectionsStringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3137,11 +3151,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.CollectionsIntProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsIntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3165,13 +3181,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsIntProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsIntProperty, _types.CollectionsIntProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsIntProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsIntProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsIntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsIntProperty or + ~typetest.property.valuetypes.types.CollectionsIntProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3310,11 +3326,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.CollectionsModelProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.CollectionsModelProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3338,13 +3356,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.CollectionsModelProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.CollectionsModelProperty, _types.CollectionsModelProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: CollectionsModelProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.CollectionsModelProperty or JSON or IO[bytes] + :param body: body. Is either a CollectionsModelProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.CollectionsModelProperty or + ~typetest.property.valuetypes.types.CollectionsModelProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3483,11 +3501,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.DictionaryStringProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.DictionaryStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3511,13 +3531,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.DictionaryStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.DictionaryStringProperty, _types.DictionaryStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: DictionaryStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.DictionaryStringProperty or JSON or IO[bytes] + :param body: body. Is either a DictionaryStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.DictionaryStringProperty or + ~typetest.property.valuetypes.types.DictionaryStringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3653,11 +3673,11 @@ def put(self, body: _models.NeverProperty, *, content_type: str = "application/j """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.NeverProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.NeverProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3681,12 +3701,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.NeverProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.NeverProperty, _types.NeverProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: NeverProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.NeverProperty or JSON or IO[bytes] + :param body: body. Is either a NeverProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.NeverProperty or + ~typetest.property.valuetypes.types.NeverProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3824,11 +3845,11 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.UnknownStringProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownStringProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3852,13 +3873,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnknownStringProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnknownStringProperty, _types.UnknownStringProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownStringProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownStringProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownStringProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownStringProperty or + ~typetest.property.valuetypes.types.UnknownStringProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -3994,11 +4015,11 @@ def put(self, body: _models.UnknownIntProperty, *, content_type: str = "applicat """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.UnknownIntProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownIntProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4022,12 +4043,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnknownIntProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnknownIntProperty, _types.UnknownIntProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownIntProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.UnknownIntProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownIntProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownIntProperty or + ~typetest.property.valuetypes.types.UnknownIntProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4163,11 +4185,11 @@ def put(self, body: _models.UnknownDictProperty, *, content_type: str = "applica """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.UnknownDictProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownDictProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4191,13 +4213,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnknownDictProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnknownDictProperty, _types.UnknownDictProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownDictProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownDictProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownDictProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownDictProperty or + ~typetest.property.valuetypes.types.UnknownDictProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4333,11 +4355,11 @@ def put(self, body: _models.UnknownArrayProperty, *, content_type: str = "applic """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.UnknownArrayProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnknownArrayProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4361,13 +4383,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnknownArrayProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnknownArrayProperty, _types.UnknownArrayProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnknownArrayProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnknownArrayProperty or JSON or IO[bytes] + :param body: body. Is either a UnknownArrayProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnknownArrayProperty or + ~typetest.property.valuetypes.types.UnknownArrayProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4505,11 +4527,11 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.StringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.StringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4533,13 +4555,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.StringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.StringLiteralProperty, _types.StringLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: StringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.StringLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a StringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.StringLiteralProperty or + ~typetest.property.valuetypes.types.StringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4675,11 +4697,11 @@ def put(self, body: _models.IntLiteralProperty, *, content_type: str = "applicat """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.IntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.IntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4703,12 +4725,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.IntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.IntLiteralProperty, _types.IntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: IntLiteralProperty, JSON, IO[bytes] Required. - :type body: ~typetest.property.valuetypes.models.IntLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a IntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.IntLiteralProperty or + ~typetest.property.valuetypes.types.IntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -4844,11 +4867,11 @@ def put(self, body: _models.FloatLiteralProperty, *, content_type: str = "applic """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put(self, body: _types.FloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.FloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4872,13 +4895,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.FloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.FloatLiteralProperty, _types.FloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: FloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.FloatLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a FloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.FloatLiteralProperty or + ~typetest.property.valuetypes.types.FloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5016,11 +5039,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.BooleanLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.BooleanLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5044,13 +5069,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.BooleanLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.BooleanLiteralProperty, _types.BooleanLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: BooleanLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.BooleanLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a BooleanLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.BooleanLiteralProperty or + ~typetest.property.valuetypes.types.BooleanLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5189,11 +5214,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.UnionStringLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionStringLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5217,14 +5244,15 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionStringLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, + body: Union[_models.UnionStringLiteralProperty, _types.UnionStringLiteralProperty, IO[bytes]], + **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionStringLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionStringLiteralProperty or JSON or - IO[bytes] + :param body: body. Is either a UnionStringLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionStringLiteralProperty or + ~typetest.property.valuetypes.types.UnionStringLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5362,11 +5390,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.UnionIntLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionIntLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5390,13 +5420,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionIntLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionIntLiteralProperty, _types.UnionIntLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionIntLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionIntLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a UnionIntLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionIntLiteralProperty or + ~typetest.property.valuetypes.types.UnionIntLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5535,11 +5565,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.UnionFloatLiteralProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionFloatLiteralProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5563,13 +5595,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionFloatLiteralProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionFloatLiteralProperty, _types.UnionFloatLiteralProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionFloatLiteralProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionFloatLiteralProperty or JSON or IO[bytes] + :param body: body. Is either a UnionFloatLiteralProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionFloatLiteralProperty or + ~typetest.property.valuetypes.types.UnionFloatLiteralProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: @@ -5707,11 +5739,13 @@ def put( """ @overload - def put(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def put( + self, body: _types.UnionEnumValueProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> None: """Put operation. :param body: body. Required. - :type body: JSON + :type body: ~typetest.property.valuetypes.types.UnionEnumValueProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -5735,13 +5769,13 @@ def put(self, body: IO[bytes], *, content_type: str = "application/json", **kwar """ def put( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.UnionEnumValueProperty, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.UnionEnumValueProperty, _types.UnionEnumValueProperty, IO[bytes]], **kwargs: Any ) -> None: """Put operation. - :param body: body. Is one of the following types: UnionEnumValueProperty, JSON, IO[bytes] - Required. - :type body: ~typetest.property.valuetypes.models.UnionEnumValueProperty or JSON or IO[bytes] + :param body: body. Is either a UnionEnumValueProperty type or a IO[bytes] type. Required. + :type body: ~typetest.property.valuetypes.models.UnionEnumValueProperty or + ~typetest.property.valuetypes.types.UnionEnumValueProperty or IO[bytes] :return: None :rtype: None :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/types.py index 2e7284054217..cb4f27eb2e28 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-property-valuetypes/typetest/property/valuetypes/types.py @@ -1,7 +1,5 @@ # coding=utf-8 -import datetime -import decimal from typing import Any, Literal, TYPE_CHECKING, Union from typing_extensions import Required, TypedDict @@ -15,7 +13,7 @@ class BooleanLiteralProperty(TypedDict, total=False): """Model with a boolean literal property. :ivar property: Property. Required. Default value is True. - :vartype property: bool + :vartype property: Literal[True] """ property: Required[Literal[True]] @@ -37,10 +35,10 @@ class BytesProperty(TypedDict, total=False): """Model with a bytes property. :ivar property: Property. Required. - :vartype property: bytes + :vartype property: str """ - property: Required[bytes] + property: Required[str] """Property. Required.""" @@ -59,7 +57,7 @@ class CollectionsModelProperty(TypedDict, total=False): """Model with collection model properties. :ivar property: Property. Required. - :vartype property: list[~typetest.property.valuetypes.models.InnerModel] + :vartype property: list["InnerModel"] """ property: Required[list["InnerModel"]] @@ -81,10 +79,10 @@ class DatetimeProperty(TypedDict, total=False): """Model with a datetime property. :ivar property: Property. Required. - :vartype property: ~datetime.datetime + :vartype property: str """ - property: Required[datetime.datetime] + property: Required[str] """Property. Required.""" @@ -92,10 +90,10 @@ class Decimal128Property(TypedDict, total=False): """Model with a decimal128 property. :ivar property: Property. Required. - :vartype property: ~decimal.Decimal + :vartype property: float """ - property: Required[decimal.Decimal] + property: Required[float] """Property. Required.""" @@ -103,10 +101,10 @@ class DecimalProperty(TypedDict, total=False): """Model with a decimal property. :ivar property: Property. Required. - :vartype property: ~decimal.Decimal + :vartype property: float """ - property: Required[decimal.Decimal] + property: Required[float] """Property. Required.""" @@ -125,10 +123,10 @@ class DurationProperty(TypedDict, total=False): """Model with a duration property. :ivar property: Property. Required. - :vartype property: ~datetime.timedelta + :vartype property: str """ - property: Required[datetime.timedelta] + property: Required[str] """Property. Required.""" @@ -136,7 +134,7 @@ class EnumProperty(TypedDict, total=False): """Model with enum properties. :ivar property: Property. Required. Known values are: "ValueOne" and "ValueTwo". - :vartype property: str or ~typetest.property.valuetypes.models.FixedInnerEnum + :vartype property: Union[str, "FixedInnerEnum"] """ property: Required[Union[str, "FixedInnerEnum"]] @@ -147,7 +145,7 @@ class ExtensibleEnumProperty(TypedDict, total=False): """Model with extensible enum properties. :ivar property: Property. Required. Known values are: "ValueOne" and "ValueTwo". - :vartype property: str or ~typetest.property.valuetypes.models.InnerEnum + :vartype property: Union[str, "InnerEnum"] """ property: Required[Union[str, "InnerEnum"]] @@ -191,7 +189,7 @@ class IntLiteralProperty(TypedDict, total=False): """Model with a int literal property. :ivar property: Property. Required. Default value is 42. - :vartype property: int + :vartype property: Literal[42] """ property: Required[Literal[42]] @@ -213,7 +211,7 @@ class ModelProperty(TypedDict, total=False): """Model with model properties. :ivar property: Property. Required. - :vartype property: ~typetest.property.valuetypes.models.InnerModel + :vartype property: "InnerModel" """ property: Required["InnerModel"] @@ -228,7 +226,7 @@ class StringLiteralProperty(TypedDict, total=False): """Model with a string literal property. :ivar property: Property. Required. Default value is "hello". - :vartype property: str + :vartype property: Literal["hello"] """ property: Required[Literal["hello"]] @@ -251,7 +249,7 @@ class UnionEnumValueProperty(TypedDict, total=False): are looking for. :ivar property: Property. Required. ENUM_VALUE2. - :vartype property: str or ~typetest.property.valuetypes.models.ENUM_VALUE2 + :vartype property: Literal[ExtendedEnum.ENUM_VALUE2] """ property: Required[Literal[ExtendedEnum.ENUM_VALUE2]] @@ -262,7 +260,7 @@ class UnionFloatLiteralProperty(TypedDict, total=False): """Model with a union of float literal as property. :ivar property: Property. Required. Is one of the following types: float - :vartype property: float or float + :vartype property: float """ property: Required[float] @@ -273,7 +271,7 @@ class UnionIntLiteralProperty(TypedDict, total=False): """Model with a union of int literal as property. :ivar property: Property. Required. Is either a Literal[42] type or a Literal[43] type. - :vartype property: int or int + :vartype property: Literal[42, 43] """ property: Required[Literal[42, 43]] @@ -285,7 +283,7 @@ class UnionStringLiteralProperty(TypedDict, total=False): :ivar property: Property. Required. Is either a Literal["hello"] type or a Literal["world"] type. - :vartype property: str or str + :vartype property: Literal["hello", "world"] """ property: Required[Literal["hello", "world"]] @@ -296,7 +294,7 @@ class UnknownArrayProperty(TypedDict, total=False): """Model with a property unknown, and the data is an array. :ivar property: Property. Required. - :vartype property: any + :vartype property: Any """ property: Required[Any] @@ -307,7 +305,7 @@ class UnknownDictProperty(TypedDict, total=False): """Model with a property unknown, and the data is a dictionnary. :ivar property: Property. Required. - :vartype property: any + :vartype property: Any """ property: Required[Any] @@ -318,7 +316,7 @@ class UnknownIntProperty(TypedDict, total=False): """Model with a property unknown, and the data is a int32. :ivar property: Property. Required. - :vartype property: any + :vartype property: Any """ property: Required[Any] @@ -329,7 +327,7 @@ class UnknownStringProperty(TypedDict, total=False): """Model with a property unknown, and the data is a string. :ivar property: Property. Required. - :vartype property: any + :vartype property: Any """ property: Required[Any] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/pyproject.toml index c40f41e696d2..c9fe36603101 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-scalar/typetest/scalar/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/pyproject.toml index b9b86fead923..48016023f999 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/operations/_operations.py index c74045ff0089..266b026b4e94 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/operations/_operations.py @@ -20,7 +20,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import ( @@ -142,11 +142,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -170,12 +170,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", """ async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Literal["a", "b", "c"] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest, IO[bytes]] = _Unset, + *, + prop: Literal["a", "b", "c"] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest or IO[bytes] :keyword prop: Is one of the following types: Literal["a"], Literal["b"], Literal["c"] Required. :paramtype prop: str or str or str @@ -321,11 +325,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest1, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest1 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -350,15 +354,15 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", async def send( self, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SendRequest1, IO[bytes]] = _Unset, *, prop: Union[Literal["b"], Literal["c"], str] = _Unset, **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest1, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest1 or IO[bytes] :keyword prop: Is one of the following types: Literal["b"], Literal["c"], str Required. :paramtype prop: str or str or str :return: None @@ -507,11 +511,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest2, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -536,15 +540,15 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", async def send( self, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SendRequest2, IO[bytes]] = _Unset, *, prop: Union[str, _models.StringExtensibleNamedUnion] = _Unset, **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest2, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest2 or IO[bytes] :keyword prop: Known values are: "b" and "c". Required. :paramtype prop: str or ~typetest.union.models.StringExtensibleNamedUnion :return: None @@ -687,11 +691,11 @@ async def send(self, *, prop: Literal[1, 2, 3], content_type: str = "application """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest3, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -715,12 +719,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", """ async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Literal[1, 2, 3] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest3, IO[bytes]] = _Unset, + *, + prop: Literal[1, 2, 3] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest3, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest3 or IO[bytes] :keyword prop: Is one of the following types: Literal[1], Literal[2], Literal[3] Required. :paramtype prop: int or int or int :return: None @@ -863,11 +871,11 @@ async def send(self, *, prop: float, content_type: str = "application/json", **k """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest4, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest4 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -890,11 +898,13 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", :raises ~corehttp.exceptions.HttpResponseError: """ - async def send(self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: float = _Unset, **kwargs: Any) -> None: + async def send( + self, body: Union[JSON, _types.SendRequest4, IO[bytes]] = _Unset, *, prop: float = _Unset, **kwargs: Any + ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest4, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest4 or IO[bytes] :keyword prop: Is one of the following types: float Required. :paramtype prop: float or float or float :return: None @@ -1039,11 +1049,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest5, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest5 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1067,12 +1077,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", """ async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Union[_models.Cat, _models.Dog] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest5, IO[bytes]] = _Unset, + *, + prop: Union[_models.Cat, _models.Dog] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest5, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest5 or IO[bytes] :keyword prop: Is either a Cat type or a Dog type. Required. :paramtype prop: ~typetest.union.models.Cat or ~typetest.union.models.Dog :return: None @@ -1217,11 +1231,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest6, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest6 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1245,12 +1259,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", """ async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.EnumsOnlyCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest6, IO[bytes]] = _Unset, + *, + prop: _models.EnumsOnlyCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest6, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest6 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.EnumsOnlyCases :return: None @@ -1395,11 +1413,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest7, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest7 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1423,12 +1441,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", """ async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.StringAndArrayCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest7, IO[bytes]] = _Unset, + *, + prop: _models.StringAndArrayCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest7, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest7 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.StringAndArrayCases :return: None @@ -1573,11 +1595,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest8, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest8 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1601,12 +1623,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", """ async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.MixedLiteralsCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest8, IO[bytes]] = _Unset, + *, + prop: _models.MixedLiteralsCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest8, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest8 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.MixedLiteralsCases :return: None @@ -1751,11 +1777,11 @@ async def send( """ @overload - async def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + async def send(self, body: _types.SendRequest9, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest9 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1779,12 +1805,16 @@ async def send(self, body: IO[bytes], *, content_type: str = "application/json", """ async def send( - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.MixedTypesCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest9, IO[bytes]] = _Unset, + *, + prop: _models.MixedTypesCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest9, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest9 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.MixedTypesCases :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/operations/_operations.py index e7ae9a537c21..b1a8850f3642 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/operations/_operations.py @@ -20,7 +20,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import UnionClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer @@ -401,11 +401,11 @@ def send(self, *, prop: Literal["a", "b", "c"], content_type: str = "application """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -429,12 +429,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Literal["a", "b", "c"] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest, IO[bytes]] = _Unset, + *, + prop: Literal["a", "b", "c"] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest or IO[bytes] :keyword prop: Is one of the following types: Literal["a"], Literal["b"], Literal["c"] Required. :paramtype prop: str or str or str @@ -580,11 +584,11 @@ def send( """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest1, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest1 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -609,15 +613,15 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa def send( # pylint: disable=inconsistent-return-statements self, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SendRequest1, IO[bytes]] = _Unset, *, prop: Union[Literal["b"], Literal["c"], str] = _Unset, **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest1, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest1 or IO[bytes] :keyword prop: Is one of the following types: Literal["b"], Literal["c"], str Required. :paramtype prop: str or str or str :return: None @@ -766,11 +770,11 @@ def send( """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest2, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -795,15 +799,15 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa def send( # pylint: disable=inconsistent-return-statements self, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.SendRequest2, IO[bytes]] = _Unset, *, prop: Union[str, _models.StringExtensibleNamedUnion] = _Unset, **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest2, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest2 or IO[bytes] :keyword prop: Known values are: "b" and "c". Required. :paramtype prop: str or ~typetest.union.models.StringExtensibleNamedUnion :return: None @@ -946,11 +950,11 @@ def send(self, *, prop: Literal[1, 2, 3], content_type: str = "application/json" """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest3, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -974,12 +978,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Literal[1, 2, 3] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest3, IO[bytes]] = _Unset, + *, + prop: Literal[1, 2, 3] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest3, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest3 or IO[bytes] :keyword prop: Is one of the following types: Literal[1], Literal[2], Literal[3] Required. :paramtype prop: int or int or int :return: None @@ -1122,11 +1130,11 @@ def send(self, *, prop: float, content_type: str = "application/json", **kwargs: """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest4, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest4 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1150,12 +1158,12 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: float = _Unset, **kwargs: Any + self, body: Union[JSON, _types.SendRequest4, IO[bytes]] = _Unset, *, prop: float = _Unset, **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest4, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest4 or IO[bytes] :keyword prop: Is one of the following types: float Required. :paramtype prop: float or float or float :return: None @@ -1300,11 +1308,11 @@ def send( """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest5, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest5 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1328,12 +1336,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: Union[_models.Cat, _models.Dog] = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest5, IO[bytes]] = _Unset, + *, + prop: Union[_models.Cat, _models.Dog] = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest5, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest5 or IO[bytes] :keyword prop: Is either a Cat type or a Dog type. Required. :paramtype prop: ~typetest.union.models.Cat or ~typetest.union.models.Dog :return: None @@ -1476,11 +1488,11 @@ def send(self, *, prop: _models.EnumsOnlyCases, content_type: str = "application """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest6, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest6 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1504,12 +1516,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.EnumsOnlyCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest6, IO[bytes]] = _Unset, + *, + prop: _models.EnumsOnlyCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest6, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest6 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.EnumsOnlyCases :return: None @@ -1652,11 +1668,11 @@ def send(self, *, prop: _models.StringAndArrayCases, content_type: str = "applic """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest7, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest7 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1680,12 +1696,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.StringAndArrayCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest7, IO[bytes]] = _Unset, + *, + prop: _models.StringAndArrayCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest7, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest7 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.StringAndArrayCases :return: None @@ -1828,11 +1848,11 @@ def send(self, *, prop: _models.MixedLiteralsCases, content_type: str = "applica """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest8, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest8 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1856,12 +1876,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.MixedLiteralsCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest8, IO[bytes]] = _Unset, + *, + prop: _models.MixedLiteralsCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest8, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest8 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.MixedLiteralsCases :return: None @@ -2004,11 +2028,11 @@ def send(self, *, prop: _models.MixedTypesCases, content_type: str = "applicatio """ @overload - def send(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + def send(self, body: _types.SendRequest9, *, content_type: str = "application/json", **kwargs: Any) -> None: """send. :param body: Required. - :type body: JSON + :type body: ~typetest.union.types.SendRequest9 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2032,12 +2056,16 @@ def send(self, body: IO[bytes], *, content_type: str = "application/json", **kwa """ def send( # pylint: disable=inconsistent-return-statements - self, body: Union[JSON, IO[bytes]] = _Unset, *, prop: _models.MixedTypesCases = _Unset, **kwargs: Any + self, + body: Union[JSON, _types.SendRequest9, IO[bytes]] = _Unset, + *, + prop: _models.MixedTypesCases = _Unset, + **kwargs: Any ) -> None: """send. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, SendRequest9, IO[bytes] Required. + :type body: JSON or ~typetest.union.types.SendRequest9 or IO[bytes] :keyword prop: Required. :paramtype prop: ~typetest.union.models.MixedTypesCases :return: None diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/types.py index 117f23bb7eba..2ea601cdbf98 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/typetest-union/typetest/union/types.py @@ -35,10 +35,10 @@ class EnumsOnlyCases(TypedDict, total=False): :ivar lr: This should be receive/send the left variant. Required. Is one of the following types: Literal["left"], Literal["right"], Literal["up"], Literal["down"] - :vartype lr: str or str or str or str + :vartype lr: Literal["left", "right", "up", "down"] :ivar ud: This should be receive/send the up variant. Required. Is either a Literal["up"] type or a Literal["down"] type. - :vartype ud: str or str + :vartype ud: Literal["up", "down"] """ lr: Required[Literal["left", "right", "up", "down"]] @@ -49,194 +49,194 @@ class EnumsOnlyCases(TypedDict, total=False): Literal[\"down\"] type.""" -class GetResponse(TypedDict, total=False): - """GetResponse. +class MixedLiteralsCases(TypedDict, total=False): + """MixedLiteralsCases. + + :ivar string_literal: This should be receive/send the "a" variant. Required. Is one of the + following types: Literal["a"], Literal[2], float, Literal[True] + :vartype string_literal: Literal["a", 2, True] + :ivar int_literal: This should be receive/send the 2 variant. Required. Is one of the following + types: Literal["a"], Literal[2], float, Literal[True] + :vartype int_literal: Literal["a", 2, True] + :ivar float_literal: This should be receive/send the 3.3 variant. Required. Is one of the + following types: Literal["a"], Literal[2], float, Literal[True] + :vartype float_literal: Literal["a", 2, True] + :ivar boolean_literal: This should be receive/send the true variant. Required. Is one of the + following types: Literal["a"], Literal[2], float, Literal[True] + :vartype boolean_literal: Literal["a", 2, True] + """ + + stringLiteral: Required[Literal["a", 2, True]] + """This should be receive/send the \"a\" variant. Required. Is one of the following types: + Literal[\"a\"], Literal[2], float, Literal[True]""" + intLiteral: Required[Literal["a", 2, True]] + """This should be receive/send the 2 variant. Required. Is one of the following types: + Literal[\"a\"], Literal[2], float, Literal[True]""" + floatLiteral: Required[Literal["a", 2, True]] + """This should be receive/send the 3.3 variant. Required. Is one of the following types: + Literal[\"a\"], Literal[2], float, Literal[True]""" + booleanLiteral: Required[Literal["a", 2, True]] + """This should be receive/send the true variant. Required. Is one of the following types: + Literal[\"a\"], Literal[2], float, Literal[True]""" + + +class MixedTypesCases(TypedDict, total=False): + """MixedTypesCases. + + :ivar model: This should be receive/send the Cat variant. Required. Is one of the following + types: Cat, Literal["a"], int, bool + :vartype model: Union["Cat", Literal["a"], int, bool] + :ivar literal: This should be receive/send the "a" variant. Required. Is one of the following + types: Cat, Literal["a"], int, bool + :vartype literal: Union["Cat", Literal["a"], int, bool] + :ivar int_property: This should be receive/send the int variant. Required. Is one of the + following types: Cat, Literal["a"], int, bool + :vartype int_property: Union["Cat", Literal["a"], int, bool] + :ivar boolean: This should be receive/send the boolean variant. Required. Is one of the + following types: Cat, Literal["a"], int, bool + :vartype boolean: Union["Cat", Literal["a"], int, bool] + :ivar array: This should be receive/send 4 element with Cat, "a", int, and boolean. Required. + :vartype array: list[Union["Cat", Literal["a"], int, bool]] + """ + + model: Required[Union["Cat", Literal["a"], builtins.int, bool]] + """This should be receive/send the Cat variant. Required. Is one of the following types: Cat, + Literal[\"a\"], int, bool""" + literal: Required[Union["Cat", Literal["a"], builtins.int, bool]] + """This should be receive/send the \"a\" variant. Required. Is one of the following types: Cat, + Literal[\"a\"], int, bool""" + int: Required[Union["Cat", Literal["a"], builtins.int, bool]] + """This should be receive/send the int variant. Required. Is one of the following types: Cat, + Literal[\"a\"], int, bool""" + boolean: Required[Union["Cat", Literal["a"], builtins.int, bool]] + """This should be receive/send the boolean variant. Required. Is one of the following types: Cat, + Literal[\"a\"], int, bool""" + array: Required[list[Union["Cat", Literal["a"], builtins.int, bool]]] + """This should be receive/send 4 element with Cat, \"a\", int, and boolean. Required.""" + + +class StringAndArrayCases(TypedDict, total=False): + """StringAndArrayCases. + + :ivar string: This should be receive/send the string variant. Required. Is either a str type or + a [str] type. + :vartype string: Union[str, list[str]] + :ivar array: This should be receive/send the array variant. Required. Is either a str type or a + [str] type. + :vartype array: Union[str, list[str]] + """ + + string: Required[Union[str, list[str]]] + """This should be receive/send the string variant. Required. Is either a str type or a [str] type.""" + array: Required[Union[str, list[str]]] + """This should be receive/send the array variant. Required. Is either a str type or a [str] type.""" + + +class SendRequest(TypedDict, total=False): + """SendRequest. :ivar prop: Required. Is one of the following types: Literal["a"], Literal["b"], Literal["c"] - :vartype prop: str or str or str + :vartype prop: Literal["a", "b", "c"] """ prop: Required[Literal["a", "b", "c"]] """Required. Is one of the following types: Literal[\"a\"], Literal[\"b\"], Literal[\"c\"]""" -class GetResponse1(TypedDict, total=False): - """GetResponse1. +class SendRequest1(TypedDict, total=False): + """SendRequest1. :ivar prop: Required. Is one of the following types: Literal["b"], Literal["c"], str - :vartype prop: str or str or str + :vartype prop: Union[Literal["b"], Literal["c"], str] """ prop: Required[Union[Literal["b"], Literal["c"], str]] """Required. Is one of the following types: Literal[\"b\"], Literal[\"c\"], str""" -class GetResponse2(TypedDict, total=False): - """GetResponse2. +class SendRequest2(TypedDict, total=False): + """SendRequest2. :ivar prop: Required. Known values are: "b" and "c". - :vartype prop: str or ~typetest.union.models.StringExtensibleNamedUnion + :vartype prop: Union[str, "StringExtensibleNamedUnion"] """ prop: Required[Union[str, "StringExtensibleNamedUnion"]] """Required. Known values are: \"b\" and \"c\".""" -class GetResponse3(TypedDict, total=False): - """GetResponse3. +class SendRequest3(TypedDict, total=False): + """SendRequest3. :ivar prop: Required. Is one of the following types: Literal[1], Literal[2], Literal[3] - :vartype prop: int or int or int + :vartype prop: Literal[1, 2, 3] """ prop: Required[Literal[1, 2, 3]] """Required. Is one of the following types: Literal[1], Literal[2], Literal[3]""" -class GetResponse4(TypedDict, total=False): - """GetResponse4. +class SendRequest4(TypedDict, total=False): + """SendRequest4. :ivar prop: Required. Is one of the following types: float - :vartype prop: float or float or float + :vartype prop: float """ prop: Required[float] """Required. Is one of the following types: float""" -class GetResponse5(TypedDict, total=False): - """GetResponse5. +class SendRequest5(TypedDict, total=False): + """SendRequest5. :ivar prop: Required. Is either a Cat type or a Dog type. - :vartype prop: ~typetest.union.models.Cat or ~typetest.union.models.Dog + :vartype prop: Union["Cat", "Dog"] """ prop: Required[Union["Cat", "Dog"]] """Required. Is either a Cat type or a Dog type.""" -class GetResponse6(TypedDict, total=False): - """GetResponse6. +class SendRequest6(TypedDict, total=False): + """SendRequest6. :ivar prop: Required. - :vartype prop: ~typetest.union.models.EnumsOnlyCases + :vartype prop: "EnumsOnlyCases" """ prop: Required["EnumsOnlyCases"] """Required.""" -class GetResponse7(TypedDict, total=False): - """GetResponse7. +class SendRequest7(TypedDict, total=False): + """SendRequest7. :ivar prop: Required. - :vartype prop: ~typetest.union.models.StringAndArrayCases + :vartype prop: "StringAndArrayCases" """ prop: Required["StringAndArrayCases"] """Required.""" -class GetResponse8(TypedDict, total=False): - """GetResponse8. +class SendRequest8(TypedDict, total=False): + """SendRequest8. :ivar prop: Required. - :vartype prop: ~typetest.union.models.MixedLiteralsCases + :vartype prop: "MixedLiteralsCases" """ prop: Required["MixedLiteralsCases"] """Required.""" -class GetResponse9(TypedDict, total=False): - """GetResponse9. +class SendRequest9(TypedDict, total=False): + """SendRequest9. :ivar prop: Required. - :vartype prop: ~typetest.union.models.MixedTypesCases + :vartype prop: "MixedTypesCases" """ prop: Required["MixedTypesCases"] """Required.""" - - -class MixedLiteralsCases(TypedDict, total=False): - """MixedLiteralsCases. - - :ivar string_literal: This should be receive/send the "a" variant. Required. Is one of the - following types: Literal["a"], Literal[2], float, Literal[True] - :vartype string_literal: str or int or float or bool - :ivar int_literal: This should be receive/send the 2 variant. Required. Is one of the following - types: Literal["a"], Literal[2], float, Literal[True] - :vartype int_literal: str or int or float or bool - :ivar float_literal: This should be receive/send the 3.3 variant. Required. Is one of the - following types: Literal["a"], Literal[2], float, Literal[True] - :vartype float_literal: str or int or float or bool - :ivar boolean_literal: This should be receive/send the true variant. Required. Is one of the - following types: Literal["a"], Literal[2], float, Literal[True] - :vartype boolean_literal: str or int or float or bool - """ - - stringLiteral: Required[Literal["a", 2, True]] - """This should be receive/send the \"a\" variant. Required. Is one of the following types: - Literal[\"a\"], Literal[2], float, Literal[True]""" - intLiteral: Required[Literal["a", 2, True]] - """This should be receive/send the 2 variant. Required. Is one of the following types: - Literal[\"a\"], Literal[2], float, Literal[True]""" - floatLiteral: Required[Literal["a", 2, True]] - """This should be receive/send the 3.3 variant. Required. Is one of the following types: - Literal[\"a\"], Literal[2], float, Literal[True]""" - booleanLiteral: Required[Literal["a", 2, True]] - """This should be receive/send the true variant. Required. Is one of the following types: - Literal[\"a\"], Literal[2], float, Literal[True]""" - - -class MixedTypesCases(TypedDict, total=False): - """MixedTypesCases. - - :ivar model: This should be receive/send the Cat variant. Required. Is one of the following - types: Cat, Literal["a"], int, bool - :vartype model: ~typetest.union.models.Cat or str or int or bool - :ivar literal: This should be receive/send the "a" variant. Required. Is one of the following - types: Cat, Literal["a"], int, bool - :vartype literal: ~typetest.union.models.Cat or str or int or bool - :ivar int_property: This should be receive/send the int variant. Required. Is one of the - following types: Cat, Literal["a"], int, bool - :vartype int_property: ~typetest.union.models.Cat or str or int or bool - :ivar boolean: This should be receive/send the boolean variant. Required. Is one of the - following types: Cat, Literal["a"], int, bool - :vartype boolean: ~typetest.union.models.Cat or str or int or bool - :ivar array: This should be receive/send 4 element with Cat, "a", int, and boolean. Required. - :vartype array: list[~typetest.union.models.Cat or str or int or bool] - """ - - model: Required[Union["Cat", Literal["a"], builtins.int, bool]] - """This should be receive/send the Cat variant. Required. Is one of the following types: Cat, - Literal[\"a\"], int, bool""" - literal: Required[Union["Cat", Literal["a"], builtins.int, bool]] - """This should be receive/send the \"a\" variant. Required. Is one of the following types: Cat, - Literal[\"a\"], int, bool""" - int: Required[Union["Cat", Literal["a"], builtins.int, bool]] - """This should be receive/send the int variant. Required. Is one of the following types: Cat, - Literal[\"a\"], int, bool""" - boolean: Required[Union["Cat", Literal["a"], builtins.int, bool]] - """This should be receive/send the boolean variant. Required. Is one of the following types: Cat, - Literal[\"a\"], int, bool""" - array: Required[list[Union["Cat", Literal["a"], builtins.int, bool]]] - """This should be receive/send 4 element with Cat, \"a\", int, and boolean. Required.""" - - -class StringAndArrayCases(TypedDict, total=False): - """StringAndArrayCases. - - :ivar string: This should be receive/send the string variant. Required. Is either a str type or - a [str] type. - :vartype string: str or list[str] - :ivar array: This should be receive/send the array variant. Required. Is either a str type or a - [str] type. - :vartype array: str or list[str] - """ - - string: Required[Union[str, list[str]]] - """This should be receive/send the string variant. Required. Is either a str type or a [str] type.""" - array: Required[Union[str, list[str]]] - """This should be receive/send the array variant. Required. Is either a str type or a [str] type.""" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/pyproject.toml index f8b12c5ed503..e5bd5588aa9a 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_types.py deleted file mode 100644 index 45f53499c1a1..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_types.py +++ /dev/null @@ -1,6 +0,0 @@ -# coding=utf-8 - -from typing import Union - -UnionV2 = Union[str, int] -UnionV1 = Union[str, int] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/operations/_operations.py index 4a74686695c2..800e69092013 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ..._utils.utils import ClientMixinABC @@ -31,7 +31,6 @@ ) from .._configuration import AddedClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -71,12 +70,12 @@ async def v2_in_interface( @overload async def v2_in_interface( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV2: """v2_in_interface. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -106,11 +105,13 @@ async def v2_in_interface( params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - async def v2_in_interface(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + async def v2_in_interface( + self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV2 or ~versioning.added.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.added.models.ModelV2 :raises ~corehttp.exceptions.HttpResponseError: @@ -198,12 +199,12 @@ async def v1( @overload async def v1( - self, body: JSON, *, header_v2: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV1, *, header_v2: str, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV1: """v1. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV1 :keyword header_v2: Required. :paramtype header_v2: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -237,12 +238,12 @@ async def v1( api_versions_list=["v1", "v2"], ) async def v1( - self, body: Union[_models.ModelV1, JSON, IO[bytes]], *, header_v2: str, **kwargs: Any + self, body: Union[_models.ModelV1, _types.ModelV1, IO[bytes]], *, header_v2: str, **kwargs: Any ) -> _models.ModelV1: """v1. - :param body: Is one of the following types: ModelV1, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV1 or JSON or IO[bytes] + :param body: Is either a ModelV1 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV1 or ~versioning.added.types.ModelV1 or IO[bytes] :keyword header_v2: Required. :paramtype header_v2: str :return: ModelV1. The ModelV1 is compatible with MutableMapping @@ -327,11 +328,13 @@ async def v2( """ @overload - async def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + async def v2( + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -359,11 +362,11 @@ async def v2(self, body: IO[bytes], *, content_type: str = "application/json", * params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - async def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + async def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV2 or ~versioning.added.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.added.models.ModelV2 :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/models/_models.py index afae609dd255..fbf74206c3ee 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/models/_models.py @@ -6,7 +6,7 @@ from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - from .. import _types, models as _models + from .. import _unions, models as _models class ModelV1(_Model): @@ -26,7 +26,7 @@ class ModelV1(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Known values are: \"enumMemberV1\" and \"enumMemberV2\".""" - union_prop: "_types.UnionV1" = rest_field( + union_prop: "_unions.UnionV1" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a int type.""" @@ -37,7 +37,7 @@ def __init__( *, prop: str, enum_prop: Union[str, "_models.EnumV1"], - union_prop: "_types.UnionV1", + union_prop: "_unions.UnionV1", ) -> None: ... @overload @@ -68,7 +68,7 @@ class ModelV2(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. \"enumMember\"""" - union_prop: "_types.UnionV2" = rest_field( + union_prop: "_unions.UnionV2" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a int type.""" @@ -79,7 +79,7 @@ def __init__( *, prop: str, enum_prop: Union[str, "_models.EnumV2"], - union_prop: "_types.UnionV2", + union_prop: "_unions.UnionV2", ) -> None: ... @overload diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/operations/_operations.py index deb9ea554b56..d15ac3d1f522 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/operations/_operations.py @@ -19,14 +19,13 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import AddedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer from .._utils.utils import ClientMixinABC from .._validation import api_version_validation -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -120,11 +119,13 @@ def v2_in_interface( """ @overload - def v2_in_interface(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + def v2_in_interface( + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -154,11 +155,13 @@ def v2_in_interface( params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - def v2_in_interface(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + def v2_in_interface( + self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any + ) -> _models.ModelV2: """v2_in_interface. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV2 or ~versioning.added.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.added.models.ModelV2 :raises ~corehttp.exceptions.HttpResponseError: @@ -244,12 +247,12 @@ def v1( @overload def v1( - self, body: JSON, *, header_v2: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.ModelV1, *, header_v2: str, content_type: str = "application/json", **kwargs: Any ) -> _models.ModelV1: """v1. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV1 :keyword header_v2: Required. :paramtype header_v2: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -282,11 +285,13 @@ def v1( params_added_on={"v2": ["header_v2"]}, api_versions_list=["v1", "v2"], ) - def v1(self, body: Union[_models.ModelV1, JSON, IO[bytes]], *, header_v2: str, **kwargs: Any) -> _models.ModelV1: + def v1( + self, body: Union[_models.ModelV1, _types.ModelV1, IO[bytes]], *, header_v2: str, **kwargs: Any + ) -> _models.ModelV1: """v1. - :param body: Is one of the following types: ModelV1, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV1 or JSON or IO[bytes] + :param body: Is either a ModelV1 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV1 or ~versioning.added.types.ModelV1 or IO[bytes] :keyword header_v2: Required. :paramtype header_v2: str :return: ModelV1. The ModelV1 is compatible with MutableMapping @@ -367,11 +372,11 @@ def v2(self, body: _models.ModelV2, *, content_type: str = "application/json", * """ @overload - def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + def v2(self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~versioning.added.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -399,11 +404,11 @@ def v2(self, body: IO[bytes], *, content_type: str = "application/json", **kwarg params_added_on={"v2": ["content_type", "accept"]}, api_versions_list=["v2"], ) - def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.added.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.added.models.ModelV2 or ~versioning.added.types.ModelV2 or IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.added.models.ModelV2 :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/types.py index ae4846c5a7ab..ffb16db35d23 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-added/versioning/added/types.py @@ -14,9 +14,9 @@ class ModelV1(TypedDict, total=False): :ivar prop: Required. :vartype prop: str :ivar enum_prop: Required. Known values are: "enumMemberV1" and "enumMemberV2". - :vartype enum_prop: str or ~versioning.added.models.EnumV1 + :vartype enum_prop: Union[str, "EnumV1"] :ivar union_prop: Required. Is either a str type or a int type. - :vartype union_prop: str or int + :vartype union_prop: "_unions.UnionV1" """ prop: Required[str] @@ -33,9 +33,9 @@ class ModelV2(TypedDict, total=False): :ivar prop: Required. :vartype prop: str :ivar enum_prop: Required. "enumMember" - :vartype enum_prop: str or ~versioning.added.models.EnumV2 + :vartype enum_prop: Union[str, "EnumV2"] :ivar union_prop: Required. Is either a str type or a int type. - :vartype union_prop: str or int + :vartype union_prop: "_unions.UnionV2" """ prop: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/pyproject.toml index ca345631d45f..e0c1e19192f3 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_operations/_operations.py index 4e43fa408862..0fde93d81a25 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import MadeOptionalClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -84,12 +83,17 @@ def test( @overload def test( - self, body: JSON, *, param: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + self, + body: _types.TestModel, + *, + param: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any ) -> _models.TestModel: """test. :param body: Required. - :type body: JSON + :type body: ~versioning.madeoptional.types.TestModel :keyword param: Default value is None. :paramtype param: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -119,12 +123,13 @@ def test( """ def test( - self, body: Union[_models.TestModel, JSON, IO[bytes]], *, param: Optional[str] = None, **kwargs: Any + self, body: Union[_models.TestModel, _types.TestModel, IO[bytes]], *, param: Optional[str] = None, **kwargs: Any ) -> _models.TestModel: """test. - :param body: Is one of the following types: TestModel, JSON, IO[bytes] Required. - :type body: ~versioning.madeoptional.models.TestModel or JSON or IO[bytes] + :param body: Is either a TestModel type or a IO[bytes] type. Required. + :type body: ~versioning.madeoptional.models.TestModel or + ~versioning.madeoptional.types.TestModel or IO[bytes] :keyword param: Default value is None. :paramtype param: str :return: TestModel. The TestModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_operations/_operations.py index 15186af9f8cf..940660d101a4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_made_optional_test_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import MadeOptionalClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -59,12 +58,17 @@ async def test( @overload async def test( - self, body: JSON, *, param: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + self, + body: _types.TestModel, + *, + param: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any ) -> _models.TestModel: """test. :param body: Required. - :type body: JSON + :type body: ~versioning.madeoptional.types.TestModel :keyword param: Default value is None. :paramtype param: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -94,12 +98,13 @@ async def test( """ async def test( - self, body: Union[_models.TestModel, JSON, IO[bytes]], *, param: Optional[str] = None, **kwargs: Any + self, body: Union[_models.TestModel, _types.TestModel, IO[bytes]], *, param: Optional[str] = None, **kwargs: Any ) -> _models.TestModel: """test. - :param body: Is one of the following types: TestModel, JSON, IO[bytes] Required. - :type body: ~versioning.madeoptional.models.TestModel or JSON or IO[bytes] + :param body: Is either a TestModel type or a IO[bytes] type. Required. + :type body: ~versioning.madeoptional.models.TestModel or + ~versioning.madeoptional.types.TestModel or IO[bytes] :keyword param: Default value is None. :paramtype param: str :return: TestModel. The TestModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-madeoptional/versioning/madeoptional/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/pyproject.toml index a5d3b82d1f20..f81074dd7f49 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_operations/_operations.py index 781cdec1f110..7bce165ad516 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import RemovedClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -86,11 +85,11 @@ def v2(self, body: _models.ModelV2, *, content_type: str = "application/json", * """ @overload - def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + def v2(self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~versioning.removed.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -113,11 +112,12 @@ def v2(self, body: IO[bytes], *, content_type: str = "application/json", **kwarg :raises ~corehttp.exceptions.HttpResponseError: """ - def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.removed.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.removed.models.ModelV2 or ~versioning.removed.types.ModelV2 or + IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.removed.models.ModelV2 :raises ~corehttp.exceptions.HttpResponseError: @@ -198,12 +198,14 @@ def model_v3( """ @overload - def model_v3(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV3: + def model_v3( + self, body: _types.ModelV3, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV3: """This operation will pass different paths and different request bodies based on different versions. :param body: Required. - :type body: JSON + :type body: ~versioning.removed.types.ModelV3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -227,12 +229,13 @@ def model_v3(self, body: IO[bytes], *, content_type: str = "application/json", * :raises ~corehttp.exceptions.HttpResponseError: """ - def model_v3(self, body: Union[_models.ModelV3, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV3: + def model_v3(self, body: Union[_models.ModelV3, _types.ModelV3, IO[bytes]], **kwargs: Any) -> _models.ModelV3: """This operation will pass different paths and different request bodies based on different versions. - :param body: Is one of the following types: ModelV3, JSON, IO[bytes] Required. - :type body: ~versioning.removed.models.ModelV3 or JSON or IO[bytes] + :param body: Is either a ModelV3 type or a IO[bytes] type. Required. + :type body: ~versioning.removed.models.ModelV3 or ~versioning.removed.types.ModelV3 or + IO[bytes] :return: ModelV3. The ModelV3 is compatible with MutableMapping :rtype: ~versioning.removed.models.ModelV3 :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_types.py deleted file mode 100644 index d8bb21ff55f9..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_types.py +++ /dev/null @@ -1,5 +0,0 @@ -# coding=utf-8 - -from typing import Union - -UnionV2 = Union[str, float] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_operations/_operations.py index 259e13970da5..189283e460cd 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_removed_model_v3_request, build_removed_v2_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import RemovedClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -51,11 +50,13 @@ async def v2( """ @overload - async def v2(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV2: + async def v2( + self, body: _types.ModelV2, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV2: """v2. :param body: Required. - :type body: JSON + :type body: ~versioning.removed.types.ModelV2 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -78,11 +79,12 @@ async def v2(self, body: IO[bytes], *, content_type: str = "application/json", * :raises ~corehttp.exceptions.HttpResponseError: """ - async def v2(self, body: Union[_models.ModelV2, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV2: + async def v2(self, body: Union[_models.ModelV2, _types.ModelV2, IO[bytes]], **kwargs: Any) -> _models.ModelV2: """v2. - :param body: Is one of the following types: ModelV2, JSON, IO[bytes] Required. - :type body: ~versioning.removed.models.ModelV2 or JSON or IO[bytes] + :param body: Is either a ModelV2 type or a IO[bytes] type. Required. + :type body: ~versioning.removed.models.ModelV2 or ~versioning.removed.types.ModelV2 or + IO[bytes] :return: ModelV2. The ModelV2 is compatible with MutableMapping :rtype: ~versioning.removed.models.ModelV2 :raises ~corehttp.exceptions.HttpResponseError: @@ -165,12 +167,14 @@ async def model_v3( """ @overload - async def model_v3(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.ModelV3: + async def model_v3( + self, body: _types.ModelV3, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelV3: """This operation will pass different paths and different request bodies based on different versions. :param body: Required. - :type body: JSON + :type body: ~versioning.removed.types.ModelV3 :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -196,12 +200,13 @@ async def model_v3( :raises ~corehttp.exceptions.HttpResponseError: """ - async def model_v3(self, body: Union[_models.ModelV3, JSON, IO[bytes]], **kwargs: Any) -> _models.ModelV3: + async def model_v3(self, body: Union[_models.ModelV3, _types.ModelV3, IO[bytes]], **kwargs: Any) -> _models.ModelV3: """This operation will pass different paths and different request bodies based on different versions. - :param body: Is one of the following types: ModelV3, JSON, IO[bytes] Required. - :type body: ~versioning.removed.models.ModelV3 or JSON or IO[bytes] + :param body: Is either a ModelV3 type or a IO[bytes] type. Required. + :type body: ~versioning.removed.models.ModelV3 or ~versioning.removed.types.ModelV3 or + IO[bytes] :return: ModelV3. The ModelV3 is compatible with MutableMapping :rtype: ~versioning.removed.models.ModelV3 :raises ~corehttp.exceptions.HttpResponseError: diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/models/_models.py index 083abc9deb14..bcf944ab9227 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/models/_models.py @@ -6,7 +6,7 @@ from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - from .. import _types, models as _models + from .. import _unions, models as _models class ModelV2(_Model): @@ -26,7 +26,7 @@ class ModelV2(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. \"enumMemberV2\"""" - union_prop: "_types.UnionV2" = rest_field( + union_prop: "_unions.UnionV2" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a float type.""" @@ -37,7 +37,7 @@ def __init__( *, prop: str, enum_prop: Union[str, "_models.EnumV2"], - union_prop: "_types.UnionV2", + union_prop: "_unions.UnionV2", ) -> None: ... @overload diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/types.py index 0144f3821d40..6212f208d051 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-removed/versioning/removed/types.py @@ -14,9 +14,9 @@ class ModelV2(TypedDict, total=False): :ivar prop: Required. :vartype prop: str :ivar enum_prop: Required. "enumMemberV2" - :vartype enum_prop: str or ~versioning.removed.models.EnumV2 + :vartype enum_prop: Union[str, "EnumV2"] :ivar union_prop: Required. Is either a str type or a float type. - :vartype union_prop: str or float + :vartype union_prop: "_unions.UnionV2" """ prop: Required[str] @@ -33,7 +33,7 @@ class ModelV3(TypedDict, total=False): :ivar id: Required. :vartype id: str :ivar enum_prop: Required. Known values are: "enumMemberV1" and "enumMemberV2Preview". - :vartype enum_prop: str or ~versioning.removed.models.EnumV3 + :vartype enum_prop: Union[str, "EnumV3"] """ id: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/pyproject.toml index b3e2f1903c00..45d90bf5ef05 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_types.py deleted file mode 100644 index b302e8524e9f..000000000000 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_types.py +++ /dev/null @@ -1,5 +0,0 @@ -# coding=utf-8 - -from typing import Union - -NewUnion = Union[str, int] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_operations.py index 9446730cc0a3..9404997fdd2b 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_operations.py @@ -19,7 +19,7 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ..._utils.utils import ClientMixinABC @@ -29,7 +29,6 @@ ) from .._configuration import RenamedFromClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -69,12 +68,12 @@ async def new_op_in_new_interface( @overload async def new_op_in_new_interface( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.NewModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.NewModel: """new_op_in_new_interface. :param body: Required. - :type body: JSON + :type body: ~versioning.renamedfrom.types.NewModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -100,12 +99,13 @@ async def new_op_in_new_interface( """ async def new_op_in_new_interface( - self, body: Union[_models.NewModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.NewModel, _types.NewModel, IO[bytes]], **kwargs: Any ) -> _models.NewModel: """new_op_in_new_interface. - :param body: Is one of the following types: NewModel, JSON, IO[bytes] Required. - :type body: ~versioning.renamedfrom.models.NewModel or JSON or IO[bytes] + :param body: Is either a NewModel type or a IO[bytes] type. Required. + :type body: ~versioning.renamedfrom.models.NewModel or ~versioning.renamedfrom.types.NewModel + or IO[bytes] :return: NewModel. The NewModel is compatible with MutableMapping :rtype: ~versioning.renamedfrom.models.NewModel :raises ~corehttp.exceptions.HttpResponseError: @@ -193,12 +193,12 @@ async def new_op( @overload async def new_op( - self, body: JSON, *, new_query: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.NewModel, *, new_query: str, content_type: str = "application/json", **kwargs: Any ) -> _models.NewModel: """new_op. :param body: Required. - :type body: JSON + :type body: ~versioning.renamedfrom.types.NewModel :keyword new_query: Required. :paramtype new_query: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -228,12 +228,13 @@ async def new_op( """ async def new_op( - self, body: Union[_models.NewModel, JSON, IO[bytes]], *, new_query: str, **kwargs: Any + self, body: Union[_models.NewModel, _types.NewModel, IO[bytes]], *, new_query: str, **kwargs: Any ) -> _models.NewModel: """new_op. - :param body: Is one of the following types: NewModel, JSON, IO[bytes] Required. - :type body: ~versioning.renamedfrom.models.NewModel or JSON or IO[bytes] + :param body: Is either a NewModel type or a IO[bytes] type. Required. + :type body: ~versioning.renamedfrom.models.NewModel or ~versioning.renamedfrom.types.NewModel + or IO[bytes] :keyword new_query: Required. :paramtype new_query: str :return: NewModel. The NewModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/aio/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/models/_models.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/models/_models.py index 855e563da3de..6965f7bd3c93 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/models/_models.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/models/_models.py @@ -6,7 +6,7 @@ from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - from .. import _types, models as _models + from .. import _unions, models as _models class NewModel(_Model): @@ -26,7 +26,7 @@ class NewModel(_Model): name="enumProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. \"newEnumMember\"""" - union_prop: "_types.NewUnion" = rest_field( + union_prop: "_unions.NewUnion" = rest_field( name="unionProp", visibility=["read", "create", "update", "delete", "query"] ) """Required. Is either a str type or a int type.""" @@ -37,7 +37,7 @@ def __init__( *, new_prop: str, enum_prop: Union[str, "_models.NewEnum"], - union_prop: "_types.NewUnion", + union_prop: "_unions.NewUnion", ) -> None: ... @overload diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/operations/_operations.py index b8f5d4335f4d..c8977ccd8032 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import RenamedFromClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -106,12 +105,12 @@ def new_op_in_new_interface( @overload def new_op_in_new_interface( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.NewModel, *, content_type: str = "application/json", **kwargs: Any ) -> _models.NewModel: """new_op_in_new_interface. :param body: Required. - :type body: JSON + :type body: ~versioning.renamedfrom.types.NewModel :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -137,12 +136,13 @@ def new_op_in_new_interface( """ def new_op_in_new_interface( - self, body: Union[_models.NewModel, JSON, IO[bytes]], **kwargs: Any + self, body: Union[_models.NewModel, _types.NewModel, IO[bytes]], **kwargs: Any ) -> _models.NewModel: """new_op_in_new_interface. - :param body: Is one of the following types: NewModel, JSON, IO[bytes] Required. - :type body: ~versioning.renamedfrom.models.NewModel or JSON or IO[bytes] + :param body: Is either a NewModel type or a IO[bytes] type. Required. + :type body: ~versioning.renamedfrom.models.NewModel or ~versioning.renamedfrom.types.NewModel + or IO[bytes] :return: NewModel. The NewModel is compatible with MutableMapping :rtype: ~versioning.renamedfrom.models.NewModel :raises ~corehttp.exceptions.HttpResponseError: @@ -230,12 +230,12 @@ def new_op( @overload def new_op( - self, body: JSON, *, new_query: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.NewModel, *, new_query: str, content_type: str = "application/json", **kwargs: Any ) -> _models.NewModel: """new_op. :param body: Required. - :type body: JSON + :type body: ~versioning.renamedfrom.types.NewModel :keyword new_query: Required. :paramtype new_query: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -265,12 +265,13 @@ def new_op( """ def new_op( - self, body: Union[_models.NewModel, JSON, IO[bytes]], *, new_query: str, **kwargs: Any + self, body: Union[_models.NewModel, _types.NewModel, IO[bytes]], *, new_query: str, **kwargs: Any ) -> _models.NewModel: """new_op. - :param body: Is one of the following types: NewModel, JSON, IO[bytes] Required. - :type body: ~versioning.renamedfrom.models.NewModel or JSON or IO[bytes] + :param body: Is either a NewModel type or a IO[bytes] type. Required. + :type body: ~versioning.renamedfrom.models.NewModel or ~versioning.renamedfrom.types.NewModel + or IO[bytes] :keyword new_query: Required. :paramtype new_query: str :return: NewModel. The NewModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/types.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/types.py index fec7960a4a4d..5e84e1269146 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/types.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-renamedfrom/versioning/renamedfrom/types.py @@ -14,9 +14,9 @@ class NewModel(TypedDict, total=False): :ivar new_prop: Required. :vartype new_prop: str :ivar enum_prop: Required. "newEnumMember" - :vartype enum_prop: str or ~versioning.renamedfrom.models.NewEnum + :vartype enum_prop: Union[str, "NewEnum"] :ivar union_prop: Required. Is either a str type or a int type. - :vartype union_prop: str or int + :vartype union_prop: "_unions.NewUnion" """ newProp: Required[str] diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/pyproject.toml index af6124d382df..43c57b3ecd79 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-returntypechangedfrom/versioning/returntypechangedfrom/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/CHANGELOG.md b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/CHANGELOG.md index 628743d283a9..b957b2575b48 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/CHANGELOG.md +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/CHANGELOG.md @@ -2,4 +2,6 @@ ## 1.0.0b1 (1970-01-01) -- Initial version +### Other Changes + + - Initial version \ No newline at end of file diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/pyproject.toml b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/pyproject.toml index bb2f3e6a8065..614216bdc5e9 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/pyproject.toml +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_operations.py index 423a3b10c8ec..db6e9ab164b8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from .. import models as _models +from .. import models as _models, types as _types from .._configuration import TypeChangedFromClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Serializer from .._utils.utils import ClientMixinABC -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] @@ -78,12 +77,12 @@ def test( @overload def test( - self, body: JSON, *, param: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.TestModel, *, param: str, content_type: str = "application/json", **kwargs: Any ) -> _models.TestModel: """test. :param body: Required. - :type body: JSON + :type body: ~versioning.typechangedfrom.types.TestModel :keyword param: Required. :paramtype param: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -112,11 +111,14 @@ def test( :raises ~corehttp.exceptions.HttpResponseError: """ - def test(self, body: Union[_models.TestModel, JSON, IO[bytes]], *, param: str, **kwargs: Any) -> _models.TestModel: + def test( + self, body: Union[_models.TestModel, _types.TestModel, IO[bytes]], *, param: str, **kwargs: Any + ) -> _models.TestModel: """test. - :param body: Is one of the following types: TestModel, JSON, IO[bytes] Required. - :type body: ~versioning.typechangedfrom.models.TestModel or JSON or IO[bytes] + :param body: Is either a TestModel type or a IO[bytes] type. Required. + :type body: ~versioning.typechangedfrom.models.TestModel or + ~versioning.typechangedfrom.types.TestModel or IO[bytes] :keyword param: Required. :paramtype param: str :return: TestModel. The TestModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_utils/model_base.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_utils/model_base.py index 99877baf4b2f..972617ba9ad8 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_utils/model_base.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_utils/model_base.py @@ -103,6 +103,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -295,6 +318,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -324,6 +353,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -419,21 +452,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -443,7 +476,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -478,19 +511,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -503,10 +536,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -558,7 +592,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_utils/serialization.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_utils/serialization.py index 8e648e299998..4172d811ae21 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_utils/serialization.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/_utils/serialization.py @@ -514,6 +514,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1103,6 +1107,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1375,6 +1434,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1387,6 +1450,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1948,6 +2015,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_operations.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_operations.py index 1603c7d2c071..85e50ebed8a4 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_operations.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_operations.py @@ -19,13 +19,12 @@ from corehttp.runtime.pipeline import PipelineResponse from corehttp.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._operations._operations import build_type_changed_from_test_request from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.utils import ClientMixinABC from .._configuration import TypeChangedFromClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -54,12 +53,12 @@ async def test( @overload async def test( - self, body: JSON, *, param: str, content_type: str = "application/json", **kwargs: Any + self, body: _types.TestModel, *, param: str, content_type: str = "application/json", **kwargs: Any ) -> _models.TestModel: """test. :param body: Required. - :type body: JSON + :type body: ~versioning.typechangedfrom.types.TestModel :keyword param: Required. :paramtype param: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -89,12 +88,13 @@ async def test( """ async def test( - self, body: Union[_models.TestModel, JSON, IO[bytes]], *, param: str, **kwargs: Any + self, body: Union[_models.TestModel, _types.TestModel, IO[bytes]], *, param: str, **kwargs: Any ) -> _models.TestModel: """test. - :param body: Is one of the following types: TestModel, JSON, IO[bytes] Required. - :type body: ~versioning.typechangedfrom.models.TestModel or JSON or IO[bytes] + :param body: Is either a TestModel type or a IO[bytes] type. Required. + :type body: ~versioning.typechangedfrom.models.TestModel or + ~versioning.typechangedfrom.types.TestModel or IO[bytes] :keyword param: Required. :paramtype param: str :return: TestModel. The TestModel is compatible with MutableMapping diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_operations/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/aio/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/models/_patch.py b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/models/_patch.py index e9ae92835196..bbe39eaf695d 100644 --- a/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/models/_patch.py +++ b/eng/tools/azure-sdk-tools/emitter/generated/unbranded/versioning-typechangedfrom/versioning/typechangedfrom/models/_patch.py @@ -5,9 +5,8 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk():